2016-09-11 2 views
1

목록 목록에서 값을 검색하고 바꿔야합니다.중첩 목록의 값을 검색하고 바꿀 수있는 방법

  1. Flatten a nested list
  2. Search for and replace a value
  3. Regroup the flat list into a list of lists

내 현재 코드는 내가 그것을 할 필요가 다음 더 복잡하다고 느낀다 그러나 작동 : 나는에 함께 답변을 자갈길했습니다. 이 일을하는보다 우아한 방법이 있습니까?

# Create test data- a list of lists which each contain 2 items 
numbers = list(range(10)) 
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)] 

# Flatten the list of lists 
flat_list = [item for sublist in list_of_lists for item in sublist] 
# Search for and replace values 
modified_list = [-1 if e > 5 else e for e in flat_list] 
# Regroup into a list of lists 
regrouped_list_of_lists = [modified_list[i:i+2] for i in range(0, len(modified_list), 2)] 
+0

이것은 아마도 그것을하는 가장 Pythonic 방법입니다. 작동하고 읽을 수있는 경우 수정하지 마세요. – TheLazyScripter

+0

@TheLazyScripter * 작동하고 읽을 수있는 경우 수정하지 마세요 *이 경우가 아닙니다. –

답변

2

중첩 된리스트 통합의 하위 목록의 교체를 확인 평평하고 재편성 할 필요없이 :

numbers = list(range(10)) 
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)] 
# here 
list_of_lists = [[-1 if e > 5 else e for e in sublist] for sublist in list_of_lists] 
2
이미 지능형리스트를 사용하고

, 단지 그들을 결합 :

replaced_list_of_lists = [ 
      [-1 if e > 5 else e for e in inner_list] 
       for inner_list in list_of_lists 
     ] 
+0

좋은 답변이라고 확신하지 못합니다. List comprehension은 가독성에 이미 많은 것을 추가하고, 그것들을 결합하는 것이별로 도움이되지 않습니다. –

+0

그럼 분명히 일부 코드가 제거되었으므로 필자는 목록 작성을 많이 사용하지 않도록 노력하고 있습니다. –

+0

@AntoineBolvy 그러나 플랫 링/대체/재결합의 원래 솔루션은 원래 목록의 형식을 정확히 알고있는 경우에만 작동합니다. 일반적인 솔루션을 원한다면 목록 내장 또는 중첩 for 루프가 필요합니다. –

관련 문제