Python 列表理解“;翻译“;
有人能把这个列表理解成多行,真的很难理解它Python 列表理解“;翻译“;,python,python-3.x,list-comprehension,Python,Python 3.x,List Comprehension,有人能把这个列表理解成多行,真的很难理解它 friends = [i for x, i in enumerate(friends) if (x+1) % action] 如果扩大,应该是这样。我创建了一个名为temp\u list的列表,为了清晰起见,我添加了print temp_list = [] for x, i in enumerate(friends): if (x+1) % action: temp_list.append(i) friends = temp
friends = [i for x, i in enumerate(friends) if (x+1) % action]
如果扩大,应该是这样。我创建了一个名为
temp\u list
的列表,为了清晰起见,我添加了print
temp_list = []
for x, i in enumerate(friends):
if (x+1) % action:
temp_list.append(i)
friends = temp_list
print(friends)
展开时,它是这样的:
friends = [] # Intialize the friends list
# For loop with enumerate function where x is the index and i the value
for x, i in enumerate(friends):
if (x+1) % action:
friends.append(i)
由于您正在使用enumerate迭代
朋友
,因此我们可以假设朋友
中已经有一些值
列表理解是将friends
list的原始值替换为作为理解逻辑输出的另一个列表。注意所有这些都是在一行中完成的
如果我们打破了对扩展形式的理解,我们就不能迭代列表并同时更改列表(我们可以这样做,但不建议这样做,我们可能会得到错误的值)
因此,上述列表理解的扩展形式如下所示:
temp = []
for x, i in enumerate(friends):
if (x+1) % action:
temp.append(i)
friends = temp
请注意,这是极其误导的
i
通常用于匿名索引,x
用于匿名值。但是enumerate
将它们生成为(索引,值)
对,因此x
实际上是这里的索引,i
是值。这就像有人故意混淆一样,这是错误的;由于它不使用临时的列表
,因此在开始循环之前,它会删除对他们正在迭代的朋友
的先前引用,因此它总是以一个空的列表
@ShadowRanger是的,你是对的。感谢您更正此问题。:)