Jos*_*osh 190 python list-comprehension
这是我试图变成列表理解的代码:
table = ''
for index in xrange(256):
if index in ords_to_keep:
table += chr(index)
else:
table += replace_with
Run Code Online (Sandbox Code Playgroud)
有没有办法将else语句添加到此理解中?
table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)
Run Code Online (Sandbox Code Playgroud)
Amb*_*ber 310
语法a if b else c是Python中的三元运算符,它评估a条件b是否为真 - 否则,它的计算结果为c.它可以用在理解语句中:
>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
所以对你的例子来说,
table = ''.join(chr(index) if index in ords_to_keep else replace_with
for index in xrange(15))
Run Code Online (Sandbox Code Playgroud)
Mic*_*zek 15
如果你想要一个else你不想过滤列表理解,你希望它迭代每个值.您可以将其true-value if cond else false-value用作语句,并从末尾删除过滤器:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
Run Code Online (Sandbox Code Playgroud)
要else在python编程中使用列表推导,您可以尝试下面的代码片段.这将解决您的问题,该代码段在python 2.7和python 3.5上进行测试.
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
Run Code Online (Sandbox Code Playgroud)
是,else可以在带有条件表达式(“三元运算符”)的理解内的Python中使用:list
>>> [("A" if b=="e" else "c") for b in "comprehension"]
['c', 'c', 'c', 'c', 'c', 'A', 'c', 'A', 'c', 'c', 'c', 'c', 'c']
Run Code Online (Sandbox Code Playgroud)
在这里,括号“()”只是为了强调条件表达式,它们不是必需的(运算符优先级)。
另外,可以嵌套几个表达式,从而导致更多elses和更难阅读的代码:
>>> ["A" if b=="e" else "d" if True else "x" for b in "comprehension"]
['d', 'd', 'd', 'd', 'd', 'A', 'd', 'A', 'd', 'd', 'd', 'd', 'd']
>>>
Run Code Online (Sandbox Code Playgroud)
与此相关的是,理解也可以if在末尾包含其自身的条件:
>>> ["A" if b=="e" else "c" for b in "comprehension" if False]
[]
>>> ["A" if b=="e" else "c" for b in "comprehension" if "comprehension".index(b)%2]
['c', 'c', 'A', 'A', 'c', 'c']
Run Code Online (Sandbox Code Playgroud)
条件s?是的,if可以有多个,实际上也可以有多个for:
>>> [i for i in range(3) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
>>> [i for i in range(3) if i for _ in range(3) if _ if True if True]
[1, 1, 2, 2]
Run Code Online (Sandbox Code Playgroud)
(下划线_是Python中的有效变量名(标识符),在这里仅用于表明它实际上并未使用。它在交互模式下具有特殊含义)
可以将其用于其他条件表达式,但没有实际用途:
>>> [i for i in range(3)]
[0, 1, 2]
>>> [i for i in range(3) if i]
[1, 2]
>>> [i for i in range(3) if (True if i else False)]
[1, 2]
Run Code Online (Sandbox Code Playgroud)
理解也可以嵌套以创建“多维”列表(“数组”):
>>> [[i for j in range(i)] for i in range(3)]
[[], [1], [2, 2]]
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的,一个修真不限于创建list,即else并且if也可以使用在以同样的方式set理解:
>>> {i for i in "set comprehension"}
{'o', 'p', 'm', 'n', 'c', 'r', 'i', 't', 'h', 'e', 's', ' '}
Run Code Online (Sandbox Code Playgroud)
和一个dictionary理解:
>>> {k:v for k,v in [("key","value"), ("dict","comprehension")]}
{'key': 'value', 'dict': 'comprehension'}
Run Code Online (Sandbox Code Playgroud)
生成器表达式也使用相同的语法:
>>> for g in ("a" if b else "c" for b in "generator"):
... print(g, end="")
...
aaaaaaaaa>>>
Run Code Online (Sandbox Code Playgroud)
可以用来创建一个tuple(没有元组理解)。
| 归档时间: |
|
| 查看次数: |
97652 次 |
| 最近记录: |