简体   繁体   English

如何从列表中删除“ ”?

[英]How do I remove ' ' from a list?

I am trying to remove ' ' from the list and it gives me IndexError: list out of range我试图从列表中删除“ ”,它给了我 IndexError: list out of range

I have tried new_string.remove(' ') as well我也试过 new_string.remove(' ')

def func_name(new_string):
   for k in range(len(new_string)):
       if new_string[k] == '':
           new_string = new_string[:k] + new_string[k+1:]
   return new_string

print func_name(['Title','','This','is','a','link','.'])

print func_name(['','','Hello','World!','',''])

print func_name(['',''])

You should try a more pythonic way, like this:你应该尝试更pythonic的方式,像这样:

def func_name(new_string):
    return [s for s in new_string if s != '']

print func_name(['Title', '', 'This', 'is', 'a', 'link', '.'])

print func_name(['', '', 'Hello', 'World!', '', ''])

print func_name(['', ''])

Your problem is that the list is shortened, but the indices are still iterated as if it's the original list.您的问题是列表缩短了,但索引仍然像原始列表一样迭代。

There are better ways of implementing this (see other answers), but to fix your implementation, you can iterate in reverse order thus avoiding the "overflow":有更好的方法来实现这一点(请参阅其他答案),但要修复您的实现,您可以以相反的顺序进行迭代,从而避免“溢出”:

def remove_empty(s):
   for k in reversed(range(len(s))):
       if s[k] == '':
           del s[k]

This only works in case where you remove at most one element at each iteration.这仅适用于在每次迭代中最多删除一个元素的情况。

Note that this mutates s in place.请注意,这会使s就地发生变化。

>>> a = ['Title','','This','is','a','link','.']
>>> remove_empty(a)
>>> a
['Title','This','is','a','link','.']

check an example:检查一个例子:

x = ["don't", '', 13] 

while '' in x:
    x.remove('')

assert x == ["don't", 13]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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