파이썬에서 목록을 가로 질러 요소 제거 [복제
-
20-09-2019 - |
문제
이 질문은 이미 여기에 답이 있습니다.
Java에서는 사용하여 할 수 있습니다 Iterator
그리고 사용합니다 .remove()
반복자가 반복자가 반환 한 마지막 요소를 제거하는 반복자의 방법은 다음과 같습니다.
import java.util.*;
public class ConcurrentMod {
public static void main(String[] args) {
List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
String color = it.next();
System.out.println(color);
if (color.equals("green"))
it.remove();
}
System.out.println("At the end, colors = " + colors);
}
}
/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/
파이썬에서 어떻게 이것을 할 수 있습니까? 목록을 수정하는 동안 목록을 수정할 수 없습니다. 여기). 그리고 동등한 사람이없는 것 같습니다. Iterator
Java의 인터페이스.
해결책
반복 a 복사 목록의 :
for c in colors[:]:
if c == 'green':
colors.remove(c)
다른 팁
Python의 최상의 접근 방식은 이상적으로 ListComp에서 새로운 목록을 만드는 것입니다. [:]
오래된 것의 예를 들어 :
colors[:] = [c for c in colors if c != 'green']
아니다 colors =
일부 답변이 제안한 바와 같이, 이름 만 반창고 결국에는 오래된 "몸"에 대한 언급을 남길 것입니다. colors[:] =
모든 카운트에서 훨씬 더 좋습니다 ;-).
필터 기능을 사용할 수 있습니다.
>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>
아니면 이것을 좋아할 수도 있습니다
>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
... colors.remove('green')
제휴하지 않습니다 StackOverflow