2016-06-04 3 views
1

몇 가지 기본 프로그래밍 연습을하고 있지만 다음 코드 조각이 동일한 값을 반환하지 않는다는 것을 다소 혼란스러워합니다. 리스트 독해 구문은 목록 내 독문 자체에서 생성 된리스트에 사용 된 "not in"키워드를 거의 무시하는 것처럼 보입니다. 이 동작은 허용되지 않습니까? 이 함수는 1, 2 및 3이 정수 목록의 어딘가에 존재하면 간단히 찾습니다. 그 당시 []입니다 Truemy_lst 때문에 지능형리스트 버전에서목록 이해력 및 "not in"키워드

# Working, no list-comprehension 
def array123(lst): 
    my_lst = [] 
    for num in lst: 
    if num not in my_lst and (num == 1 or num == 2 or num == 3): 
     my_lst.append(num) 
    if sorted(my_lst) == [1, 2, 3]: 
    return True 
    else: 
    return False 

# List Comprehension 
def array123(lst): 
    my_lst = [] 
    my_lst = [num for num in lst if num not in my_lst and (num == 1 or num == 2 or num == 3)] 
    if sorted(my_lst) == [1, 2, 3]: 
    return True 
    else: 
    return False 
+1

당신의 의견 s 및 예상 결과? – AK47

+1

목록 완성 결과는 완료 될 때까지 할당되지 않습니다. 첫 번째 경우에는 'my_lst'가 루핑 중에 업데이트됩니다. 두 번째 경우에는 그렇지 않습니다. –

답변

1

if num not in my_lst 항상 반환합니다.

# List Comprehension 
def array123(lst): 
    my_lst = [] 

    my_lst = [num for num in lst 
       if num not in my_lst # always returns True for `my_lst=[]` 
         and (num == 1 or num == 2 or num == 3)] 

    print(my_lst) 

# Demo 
array123([1, 2, 3, 1, 2, 3]) 
# Output 
[1, 2, 3, 1, 2, 3] 

당신은 아마 목록의 고유 요소가 1, 2, 3입니다 있는지 확인하고 싶습니다. 여기에 set을 사용하십시오.

my_lst = [1, 2, 3, 1, 2, 3] 
b = set(my_lst) == set([1, 2, 3]) # True 

my_lst = [1, 2, 3, 1, 2, 4] 
b = set(my_lst) == set([1, 2, 3]) # False 
1

당신의 상태 not in my_list 항상 True 될 것입니다. 고유 한 요소를 작성 중이므로 set 이해력을 사용해야합니다.

my_set = {num for num in lst if num == 1 or num == 2 or num == 3} 

귀하의 if-or 조건

가 감소 할 수 있습니다

my_set = {num for num in lst if num in (1, 2, 3)} 

그리고 당신이 목록에

my_list = list(my_set) 
1

당신의 set를 변환하거나 사용 세트 : 무엇

#!python3 
_SET123 = {1,2,3} 

def array123(iterable): 
    return set(i for i in iterable if i in _SET123) == _SET123 



for x in "123", (1,2,2,2), [1,2,3], {1:"one", 3:"two", 2:"three"}: 
    print(x, array123(x)) 
관련 문제