[英]python list comprehension by step of 2
xlabels = ["first", "second", "third", "fourth"]
Is there a way to step through a list comprehension by 2? 有没有办法通过2逐步完成列表理解?
for i in range(0,len(xlabels)):
xlabels[i]=""
becomes ["" for i in xlabels]
["" for i in xlabels]
成为["" for i in xlabels]
It turns the list into blanks. 它将列表变成空白。 output: ["","","",""]
输出: ["","","",""]
what about?: 关于什么?:
for i in range(0,len(xlabels),2):
xlabels[i]=""
I want to turn every other item in the list into a blank. 我想将列表中的其他项目变为空白。 output: ["", "second", "", "fourth"]
输出: ["", "second", "", "fourth"]
Personally, I'd use a list slice and list comprehension together: 就个人而言,我会一起使用列表切片和列表推导:
>>> full_list = ['first', 'second', 'third', 'fourth', 'fifth']
>>> [element for element in full_list[::2]]
['first', 'third', 'fifth']
You are on the right track by using range()
with step. 通过使用带步长的range()
,您处于正确的轨道上。 List comprehensions tend to create a new list instead of modifying the existing one. 列表推导倾向于创建新列表而不是修改现有列表。 However, you can still do the following instead: 但是,您仍然可以执行以下操作:
>>> xlabels = [1, 2, 3, 4]
>>> [xlabels[i] if i % 2 != 0 else '' for i in range(len(xlabels))]
['', 2, '', 4]
Unless you need it to be more general, you could also do this: 除非你需要它更通用,否则你也可以这样做:
>>> xlabels = ["first", "second", "third", "fourth"]
>>> [i%2 * label for i, label in enumerate(xlabels)]
['', 'second', '', 'fourth']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.