변수가 앞에 오는 Python for-in 루프
foo = [x for x in bar if x.occupants > 1]
여기에서 인터넷 검색 및 검색을 한 후에도 이것이 무엇을하는지 알 수 없습니다. 내가 올바른 물건을 찾고 있지 않았을 수도 있지만 여기 있습니다. 이 속기의 해체에 대한 모든 의견은 대단히 감사합니다.
현재 답변은 좋지만 우리가 익숙한 패턴에 대한 구문 론적 설탕 에 대해 이야기하지 마십시오 .
예를 들어 10 개의 숫자가 있고 5보다 큰 숫자의 하위 집합이 필요하다고 가정 해 보겠습니다.
>>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]
위의 작업에서 아래의 접근 방식은 서로 완전히 동일하며 대부분의 장황한 것에서 간결하고 읽기 쉬운 비단뱀으로 이동합니다 .
접근 방식 1
result = []
for index in range(len(numbers)):
if numbers[index] > 5:
result.append(numbers[index])
print result #Prints [12, 34, 67, 37, 9, 81]
접근 방식 2 (약간 깔끔한 for-in 루프)
result = []
for number in numbers:
if number > 5:
result.append(number)
print result #Prints [12, 34, 67, 37, 9, 81]
접근법 3 (목록 이해력 입력)
result = [number for number in numbers if number > 5]
또는 더 일반적으로 :
[function(number) for number in numbers if condition(number)]
어디:
function(x)
가 필요x
하고 유용한 무언가로 변환 (예를 들어 같은 :x*x
)- 경우에
condition(x)
반환 한 후 현재 반복이 (생각 건너 뜁니다 허위-Y 값 (거짓, 없음, 빈 문자열, 빈리스트 등 ..)continue
). 함수가 거짓이 아닌 값을 반환하면 현재 값이 최종 결과 배열로 만들어집니다 (위의 변환 단계를 거칩니다).
구문을 약간 다른 방식으로 이해하려면 아래 보너스 섹션을 참조하십시오.
자세한 내용은 다른 모든 답변이 연결된 자습서를 따르십시오. List Comprehension
보너스
(약간 비단뱀 적이지만 완전성을 위해 여기에 두십시오)
위의 예는 다음과 같이 작성할 수 있습니다.
result = filter(lambda x: x > 5, numbers)
위의 일반 표현식은 다음과 같이 작성할 수 있습니다.
result = map(function, filter(condition, numbers)) #result is a list in Py2
그것은의 지능형리스트
foo
bar
속성이 점유자> 1 인 개체를 포함 하는 필터링 된 목록이 됩니다.
bar
할 수있다 list
, set
, dict
또는 기타 반복 가능한
다음은 명확히하는 예입니다.
>>> class Bar(object):
... def __init__(self, occupants):
... self.occupants = occupants
...
>>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
>>> foo = [x for x in bar if x.occupants > 1]
>>> foo
[<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]
그래서 foo는 2 개의 Bar
객체를 가지고 있지만 그들이 어떤 객체인지 어떻게 확인합니까? 더 많은 정보를 얻을 __repr__
수 Bar
있도록에 메서드를 추가 할 수 있습니다.
>>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
>>> foo
[Bar(occupants=2), Bar(occupants=3)]
이것은 점유자가> 1 인 bar의 모든 요소를 포함하는 목록을 반환합니다.
내가 말할 수있는 한 이것이 작동하는 방식은 목록 "bar"가 비어 있는지 (0) 또는 x.occupants를 통해 단일 항목 (1)으로 구성되어 있는지 확인하는 것입니다. 여기서 x는 목록 표시 줄 내에서 정의 된 항목이고 거주자의 특성이있을 수 있습니다. 따라서 foo가 호출되고 목록을 이동 한 다음 x.occupant 인 확인 조건을 통과하는 모든 항목을 반환합니다.
In a language like Java, you'd build a class called "x" where 'x' objects are then assigned to an array or similar. X would have a Field called "occupants" and each index would be checked with the x.occupants method which would return the number that is assigned to occupant. If that method returned greater than 1 (We assume an int here as a partial occupant would be odd.) the foo method (being called on the array or similar in question.) would then return an array or similar as defined in the foo method for this container array or what have you. The elements of the returned array would be the 'x' objects in the first array thingie that fit the criteria of "Greater than 1".
Python has built-in methods via list comprehension to deal with this in a much more succinct and vastly simplified way. Rather than implementing two full classes and several methods, I write that one line of code.
참고URL : https://stackoverflow.com/questions/6475314/python-for-in-loop-preceded-by-a-variable
'Development Tip' 카테고리의 다른 글
EntityManager Vs. (0) | 2020.11.08 |
---|---|
getaddrinfo : nodename 또는 servname이 제공되었거나 알려지지 않음 (0) | 2020.11.08 |
data.table에서 중복되거나 고유하지 않은 행 필터링 (0) | 2020.11.08 |
ES6 맵을 JSON.stringify하는 방법은 무엇입니까? (0) | 2020.11.08 |
WebView처럼 Windows Form에 Gecko 또는 Webkit을 임베드 할 수 있습니까? (0) | 2020.11.08 |