python []括号中使用for循环的用法 之 列表解析

小豆苗 1年前 ⋅ 3255 阅读

前面发现了一段代码,当时没看明白,现在终于明仔怎么回事了。现分享给大家看看。

前面发现的代码:

begin = datetime.date(2020, 1, 1)
end = datetime.date(2020, 12, 31)
data = [
    [str(begin + datetime.timedelta(days=i)), random.randint(1000, 25000)]
    for i in range((end - begin).days + 1)
]

原来是使用了“列表解析” - List Comprehensions

---------------------------------------------------------------------------------------------------------------------------

范例:列出1~10所有数字的平方

普通写法:

L = []
for i in range(1,11):
    L.append(i**2)
 
print L

输出为:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

而使用了列表解析的方式后的写法为:

L = [ i**2 for i in range(1,11)]
print L

输出为:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

=========================================================================

 

官方的介绍地址为https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

5.1.3. List Comprehensions
List comprehensions provide a concise way to create lists.Common applications are to make new lists where each element is the result ofsome operations applied to each member of another sequence or iterable, or tocreate a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

squares = []

for x in range(10):
    squares.append(x**2)

print(squares)

输出为:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named x that still existsafter the loop completes. We can calculate the list of squares without anyside effects using:

squares = list(map(lambda x: x**2, range(10)))
or, equivalently:

squares = [x**2 for x in range(10)]

which is more concise and readable.


全部评论: 0

    我有话说: