前面发现了一段代码,当时没看明白,现在终于明仔怎么回事了。现分享给大家看看。
前面发现的代码:
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.
注意:本文归作者所有,未经作者允许,不得转载
原文地址: http://blog.wsmee.com/post/56
版权声明:非商用-非衍生-保持署名| Creative Commons BY-NC-ND 3.0