简体   繁体   English

创建运行时长度的python列表的pythonic方法

[英]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.

相关问题 创建列表字典的 Pythonic 方法(字典理解) - Pythonic way to create a dictionary of lists (dict comprehension) pythonic将列表列表拆分为长度键控字典的方法? - pythonic way of splitting a list of lists into a length-keyed dictionary? 有没有更 Pythonic 的方式来写这个? 将多个列表填充到所需长度 - Is there a more Pythonic way to write this? Filling multiple lists to desired length 以pythonic方式创建列表列表 - Creating lists of lists in a pythonic way 创建包含在多个列表中的所有值的联合的 Pythonic 方法 - Pythonic way to create union of all values contained in multiple lists 从 pandas Dataframe 列创建列表的高效/Pythonic 方式 - Efficient/Pythonic way to create lists from pandas Dataframe column Python:处理两个列表的“Pythonic”方法是什么? - Python: What's the “Pythonic” way to process two lists? Python 比较 2 个大小列表增加的 Python 方法是什么? - Python what is the pythonic way of comparing 2 increasing in size lists? 用Python方式汇总列表和列表列表 - Pythonic way of summing lists and lists of lists 最优雅的(pythonic)方式来获取列表列表中的第 i 个元素,并创建这些第 i 个元素的列表 - Most programmatically elegant (pythonic) way to take ith element of list of lists of lists, and create lists of these ith elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM