Python 用列表推导式进行三元迭代
三元迭代是可能的吗?我这里说的简单一点,虽然这个例子其实可以用更好的方式来实现:
c = 0
list1 = [4, 6, 7, 3, 4, 5, 3, 4]
c += 1 if 4 == i for i in list1 else 0
一个更实际的例子:
strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
counter = 0
counter += 1 if True == i.startswith('U') for i in strList else 0
return counter
3 个回答
0
你还可以用列表推导式来选择你的项目,并计算列表中的元素数量。
strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
len([k for k in strList if k.startswith('U')])
1
@Jon Clements 给出了一个很棒的答案:他展示了如何用 Python 的方式来解决这个问题。如果其他 Python 程序员看到他的代码,他们会立刻明白。这就是用 Python 处理问题的正确方法。
来回答你的问题:不,这样做是不行的。三元运算符的格式是这样的:
expr1 if condition else expr2
condition
必须是一个能返回 bool
(布尔值)的东西。三元表达式会在 expr1
和 expr2
中选择一个,没别的。
当我尝试像 c += 1 if condition else 0
这样的表达式时,我很惊讶它居然能工作,并在这个答案的第一版中提到了这一点。@TokenMacGuy 指出,实际上发生的事情是:
c += (1 if condition else 0)
所以你永远无法做到你想做的事情,即使你放入一个合适的条件,而不是某种循环。上面的情况是可以的,但像这样的就会失败:
c += 1 if condition else x += 2 # syntax error on x += 2
这是因为 Python 不把赋值语句当作表达式。
你不能犯这个常见的错误:
if x = 3: # syntax error! Cannot put assignment statement here
print("x: {}".format(x))
在这里,程序员可能想用 x == 3
来测试值,但却输入了 x = 3
。Python 通过不把赋值当作表达式来保护你免于这个错误。
你既不能无意中这样做,也不能故意这样做。
6
你的“实际例子”写成了:
>>> strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
>>> sum(1 for el in strList if el.startswith('U'))
2
你提到的另一个例子(如果我理解没错的话)是:
>>> list1 = [4, 6, 7, 3, 4, 5, 3, 4]
>>> list1.count(4)
3
(或者直接改一下 strList
的例子,不过使用内置方法也没问题)