python ternary iteration with list comprehension

不想你离开。 提交于 2019-12-06 02:55:52

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