简体   繁体   中英

Remove empty strings from a list except 1st one in Python

I am trying to remove empty strings from a list except the 1st element. I have this code -

my_list = ['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1', '']
while("" in my_list[1:]) :
  my_list.remove("")
print(my_list)

But I am not getting the desires result. It's still removing the 1st element. The result I am looking for is -

['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1']

But I am getting -

['CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1']
my_list = ['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1', '']
out = [el for i, el in enumerate(my_list) if i == 0 or el]
print(out)
['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1']

You can use:

my_list = [my_list[0]] + [item for item in my_list[1:] if item != ""]

This code works by simply combining the result of the first element in the list [my_list[0]] with the filtered result you desire: [item for item in my_list[1:] if item != ""] .

The problem is that .remove will remove the first element from the list despite your while statement.

You could also do something like this

enumerates() gets both the element and the index in a for loop.


for i,e in enumerate(my_list):
    if e == '' and i != 0:
        my_list.pop(i)



Use enumerate() to get the index: Avoid removing index 0

my_list = ['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1', '']
my_list = [
    element 
    for index, element in enumerate(my_list)
    if index > 0 and element != ""
]

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