The f=[]
in the below code seems a waste of a line, but I don't know how to get around it.
1)
f=[]
for x in X:
f.append(foo(x))
2)
f=[]
[f.append(foo(x)) for x in X]
I was just wondering what the most "pythonic" way to do this is. The f=[]
line seems unpythonic.
您最好阅读有关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)
f = list(X)
copies X to f and has the same time complexity as the above according to https://wiki.python.org/moin/TimeComplexity
If you meant to specifically create a list where every element is foo(x), then yeah:
f = [foo(x) for x in X]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.