列表理解和“不在”关键字

时间:2016-06-04 20:26:59

标签: python list-comprehension

进行一些基本的编程练习,但有些困惑,发现下面的代码片段没有返回相同的值。列表推导语法似乎几乎忽略了我从列表推导本身创建的列表中使用的“not in”关键字。这种行为不被允许吗?该函数只是查找1,2和3是否存在于整数列表中的某个位置。

# 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

3 个答案:

答案 0 :(得分:1)

在列表推导版本中,True始终返回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 ,就在这里。

<head>

答案 1 :(得分: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)}

然后将set转换为列表

my_list = list(my_set)

答案 2 :(得分:1)

或使用套装:

#!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))