[英]pythonic way to create python lists of runtime length
The f=[]
in the below code seems a waste of a line, but I don't know how to get around it. 以下代码中的
f=[]
似乎浪费了一行,但我不知道如何解决。
1) 1)
f=[]
for x in X:
f.append(foo(x))
2) 2)
f=[]
[f.append(foo(x)) for x in X]
I was just wondering what the most "pythonic" way to do this is. 我只是想知道执行此操作的最“ pythonic”方式是什么。 The
f=[]
line seems unpythonic. f=[]
行似乎是不可思议的。
您最好阅读有关python中的列表推导的信息
f = [foo(x) for x in X]
f = [None]*len(X)
creates a list of None elements in the same size as X, and is O(n) 创建一个与X大小相同的None元素列表,并且为O(n)
f = list(X)
copies X to f and has the same time complexity as the above according to https://wiki.python.org/moin/TimeComplexity 根据https://wiki.python.org/moin/TimeComplexity将X复制到f并具有与上述相同的时间复杂度
If you meant to specifically create a list where every element is foo(x), then yeah: 如果要专门创建一个列表,其中每个元素都是foo(x),那么可以:
f = [foo(x) for x in X]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.