python ternary iteration with list comprehension

独自空忆成欢 提交于 2019-12-22 09:38:30

问题


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  

回答1:


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)




回答2:


@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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!