Python列出理解 [英] Python lists comprehension
问题描述
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
print numbers
>> ['1', '2', '3', '4', '5']
另一个例子:
>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
让我感到困惑的是x for x
部分.我之前已经看过几个地方,但不确定它的含义.有人可以提供更多示例并为这些示例提供解释吗?
What is confusing me is the x for x
part. I've seen it a few places before but unsure what it means. Could someone provide more examples and explanation for these examples?
推荐答案
这些结构称为列表理解.
简单示例
[x for x in iterable]
的字面意思是对于可迭代的每个元素,将该元素添加到新创建的列表中".等同于
[x for x in iterable]
literally means "for every element in iterable, add that element to newly created list" and is equivalent to
new_list = []
for x in iterable:
new_list.append(x)
逐行说明:
Loop List comprehension
--------------------------------------------------------------------------
new_list = [] [x for x in iterable]
for x in iterable: [x for x in iterable]
new_list.append(x) [x for x in iterable]
更复杂的示例
[int(x) for x in string if x.isdigit()]
可以理解为对于可迭代的每个元素,如果将x.isdigit()
应用于元素,则将对新创建的列表应用int
的结果相加".
[int(x) for x in string if x.isdigit()]
can be read as "for every element in iterable, add the result of applying int
to the element to newly created list if x.isdigit()
".
逐行说明:
Loop List comprehension
-------------------------------------------------------------------------
numbers = [] [int(x) for x in string if x.isdigit()]
for x in string: [int(x) for x in string if x.isdigit()]
if x.isdigit(): [int(x) for x in string if x.isdigit()]
numbers.append(int(x)) [int(x) for x in string if x.isdigit()]
这篇关于Python列出理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!