2017-12-28 2 views
0

나는 '제거하려고'목록에서 그것은 IndexError 저를 제공합니다 목록을 나는 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(['','']) 

답변

0

검사 예 :

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

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

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

복잡도는 O (n^2) – Elazar

2

당신은 더 시도해야을 이 같은 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(['','']) 
-1

인덱스를 반복하는 목록을 수정해서는 안됩니다. 파이썬에는이를위한 준비 도구가 있습니다. remove으로 전화하면 ValueError을 찾을 수 있습니다.

In [1]: my_list = ['a', 'b', '', ' ', 'qwerty', '', 'z', '', 123] 

In [2]: my_list.remove(2) 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-2-02b08a66ea7c> in <module>() 
----> 1 my_list.remove(2) 

ValueError: list.remove(x): x not in list 

In [3]: try: 
    ...:  while True: 
    ...:   my_list.remove('') 
    ...: except ValueError: 
    ...:  print my_list 
    ...:  
['a', 'b', ' ', 'qwerty', 'z', 123] 
1

귀하의 문제는 목록이 단축된다이지만, 원래리스트 인 것처럼 인덱스는 여전히 반복된다.

이 (다른 답변을 참조)이 구현하는 더 나은 방법이 있지만, 구현을 해결하기 위해, 당신은 따라서 "오버 플로우를"피 역순으로 반복 할 수 경우

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

이 비로소 작동 어디 각 반복마다 하나의 요소를 제거하십시오.

이 점은 s을 변경합니다.

>>> a = ['Title','','This','is','a','link','.'] 
>>> remove_empty(a) 
>>> a 
['Title','This','is','a','link','.'] 
관련 문제