thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
어떻게 말합니까 :요소가 목록에 있는지 어떻게 알 수 있습니까?
If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):
thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
어떻게 말합니까 :요소가 목록에 있는지 어떻게 알 수 있습니까?
If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):
조건을 만족하는 요소가 있는지 확인하기 위해 any()
사용 :
>>> any(item['color'] == 'red' and item['time'] != 2 for item in thelist)
False
이것은 멋집니다! any()의 괄호가 생성기로 두 배로 증가한다는 것을 올바르게 이해하고 있으므로 any()는 항목 별 항목 이해도 항목을 평가하고 조건을 만족하는 항목을 찾으면 True를 반환합니다. – Ben
파이썬의 합리적 이유 버전 (2.4 이후)에서 사용할 수있는 "생성기 표현식"입니다. 고전적인 목록 이해력을 얻기 위해'any ([...]) '라고 쓸 수도 있습니다. (generator expressions에 대한 자세한 내용은 http://www.python.org/dev/peps/pep-0289/를 참조하십시오.) – sth
그건 저에게 파이썬을 좋아하게 만드는 종류의 것입니다. – orokusaki
def colorRedAndTimeNotEqualTo2(thelist):
for i in thelist:
if i["color"] == "red" and i["time"] != 2:
return True
return False
print colorRedAndTimeNotEqualTo2([{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}])
난에 대한 thelist 통해 thelist 반복, 나는 현재 요소를 할당하고 난의 각 값에 대해 (블록의 코드의 나머지 부분을 수행)
캐치를 주셔서 감사합니다, Benson.
대부분의 목록 조작은 목록 이해에서 수행 할 수 있습니다. 다음은 색상이 빨간색 인 모든 요소에 대한 시간 목록을 만드는 방법입니다. 그러면 그 시간에 2가 존재하는지 물어볼 수 있습니다.
thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
reds = (x['time'] == 2 for x in thelist if x['color'] == red)
if False in reds:
do_stuff()
당신은 다음과 같은 변수 "빨강"을 제거하여 더욱 그 응축 할 수
:
thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
if False in (x['time'] == 2 for x in thelist if x['color'] == red):
do_stuff()
음, "찾기"하지만 당신은 지능형리스트를 사용할 수있는만큼 우아한 아무것도 :
matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
if len(matches):
m = matches[0]
# do something with m
그러나 [0]
과 len()은 지루합니다. 나는 종종 같은 배열 슬라이스 루프를 사용
matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
for m in matches[:1]:
# do something with m
"나는 많아야 하나"라고 생각했습니다. 모든 경기를 원한다면 다른 사람의 대답에 연기 할 것입니다. – jpsimons
list = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
for i in list:
if i['color'] == 'red' && i['time'] != 2:
print i
아마도 이것은 너무 애매하지만, "list"라는 이름의 지정을 피하는 것이 좋습니다. 어떤 시점에서는 목록 생성자에 대한 액세스가 필요하고이를 덮어 쓰는 것이 수치 스럽기 때문입니다. – Benson
Python은 "&&"대신 "and"를 사용합니다. – Ponkadoodle
for val in thelist:
if val['color'] == 'red' and val['time'] != 2:
#do something here
하지만 그건 사용할 수있는 권리 데이터 구조처럼은 보이지 않는다.
는 "wallacoloo"대답하고 목록의 이해/파이썬 답변 사이의 속도 차이가 있습니까? – TIMEX