简体   繁体   中英

python list comprehension by step of 2

xlabels = ["first", "second", "third", "fourth"]

Is there a way to step through a list comprehension by 2?

for i in range(0,len(xlabels)):
    xlabels[i]=""

becomes ["" 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"]

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. 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']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM