简体   繁体   English

python list comprehension by step of 2

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

相关问题 python列表理解动作步骤和条件中的function同时评价 - Evaluation of function in python list comprehension action step and condition at the same time Python 是否在每个步骤中计算列表理解条件? - Does Python calculate list comprehension condition in each step? 在 Python 中使用集合推导进行列表推导 - List comprehension with Set comprehension in Python Python 3 - 列表理解“如果不在列表中” - Python 3 - list comprehension “if not in list” Python:在列表理解本身中引用列表理解? - Python: Referring to a list comprehension in the list comprehension itself? 如何在pycharm中跳过列表理解? - how to step over list comprehension in pycharm? 如何在列表理解中添加额外的中间步骤? - How to add an extra middle step into a list comprehension? python 列表理解中的可迭代列表理解 - python iterable list comprehension in list comprehension 带有附加步骤的列表理解(将第一个元素与自身进行比较,然后将第一个元素与第二个元素进行比较,将第二个元素与第三个元素进行比较……)python - list comprehension with additional step (comparing first element to itself, then first with second, second with third,…) python 使用Python字典进行列表理解 - List Comprehension With A Python Dict
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM