Is ternary iteration possible? A simplistic version of what I mean, though this particular example could be done in a better way:
c = 0
list1 = [4, 6, 7, 3, 4, 5, 3, 4]
c += 1 if 4 == i for i in list1 else 0
A more practical example:
strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
counter = 0
counter += 1 if True == i.startswith('U') for i in strList else 0
return counter
Your "practical example" is written as:
>>> strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
>>> sum(1 for el in strList if el.startswith('U'))
2
Your other example (if I understand correctly) is:
>>> list1 = [4, 6, 7, 3, 4, 5, 3, 4]
>>> list1.count(4)
3
(or just adapt the strList
example, but nothing wrong with using builtin methods)
@Jon Clements gave you an excellent answer: how to solve the problem using Python idiom. If other Python programmers look at his code, they will understand it immediately. It's just the right way to do it using Python.
To answer your actual question: no, that does not work. The ternary operator has this form:
expr1 if condition else expr2
condition
must be something that evaluates to a bool
. The ternary expression picks one of expr1
and expr2
and that's it.
When I tried an expression like c += 1 if condition else 0
I was surprised it worked, and noted that in the first version of this answer. @TokenMacGuy pointed out that what was really happening was:
c += (1 if condition else 0)
So you can't ever do what you were trying to do, even if you put in a proper condition instead of some sort of loop. The above case would work, but something like this would fail:
c += 1 if condition else x += 2 # syntax error on x += 2
This is because Python does not consider an assignment statement to be an expression.
You can't make this common mistake:
if x = 3: # syntax error! Cannot put assignment statement here
print("x: {}".format(x))
Here the programmer likely wanted x == 3
to test the value, but typed x = 3
. Python protects from this mistake by not considering an assignment to be an expression.
You can't do it by mistake, and you can't do it on purpose either.
You can also select your items with list comprehension, and take number of elements in list.
strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
len([k for k in strList if k.startswith('U')])
来源:https://stackoverflow.com/questions/14638871/python-ternary-iteration-with-list-comprehension