Gre*_*ynn 70 python for-loop for-in-loop
foo = [x for x in bar if x.occupants > 1]
Run Code Online (Sandbox Code Playgroud)
谷歌搜索和搜索后,无法弄清楚这是做什么的.也许我没有找到合适的东西但是在这里.非常感谢任何改写这种速记的输入.
Ult*_*nct 65
目前的答案是好的,但不要谈论它们如何只是我们习以为常的某种模式的语法糖.
让我们从一个例子开始,假设我们有10个数字,我们想要一个大于5的数据的子集.
>>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]
Run Code Online (Sandbox Code Playgroud)
对于上述任务,下面的方法完全相同,从大多数冗长到简洁,可读和pythonic:
result = []
for index in range(len(numbers)):
if numbers[index] > 5:
result.append(numbers[index])
print result #Prints [12, 34, 67, 37, 9, 81]
Run Code Online (Sandbox Code Playgroud)
result = []
for number in numbers:
if number > 5:
result.append(number)
print result #Prints [12, 34, 67, 37, 9, 81]
Run Code Online (Sandbox Code Playgroud)
result = [number for number in numbers if number > 5]
Run Code Online (Sandbox Code Playgroud)
[function(number) for number in numbers if condition(number)]
Run Code Online (Sandbox Code Playgroud)
哪里:
function(x)需要一个x,并将其转换成有用的东西(例如像:x*x)condition(x)返回任何False-y值(False,None,空字符串,空列表等),然后将跳过当前迭代(想想continue).如果函数返回非False-y值,则当前值使其成为最终结果数组(并通过上面的转换步骤).要以稍微不同的方式理解语法,请查看下面的"奖励"部分.
有关详细信息,请按照教程中的所有其他答案进行链接:列表理解
(略微不是pythonic,但是为了完整起见而把它放在这里)
上面的例子可以写成:
result = filter(lambda x: x > 5, numbers)
Run Code Online (Sandbox Code Playgroud)
上面的一般表达式可以写成:
result = map(function, filter(condition, numbers)) #result is a list in Py2
Run Code Online (Sandbox Code Playgroud)
Joh*_*ooy 27
这是列表理解
foo将是bar包含属性占用者> 1的对象的筛选列表
bar可以是list,set,dict或任何其他可迭代
这是一个澄清的例子
>>> class Bar(object):
... def __init__(self, occupants):
... self.occupants = occupants
...
>>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
>>> foo = [x for x in bar if x.occupants > 1]
>>> foo
[<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]
Run Code Online (Sandbox Code Playgroud)
所以foo有2个Bar对象,但我们如何检查它们是哪些?让我们添加一个__repr__方法,Bar以便提供更多信息
>>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
>>> foo
[Bar(occupants=2), Bar(occupants=3)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76109 次 |
| 最近记录: |