进行一些基本的编程练习,但发现以下代码片段没有返回相同的值,这让我感到有点困惑。列表理解语法似乎几乎忽略了我在从列表理解本身创建的列表上使用的"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发布于 2016-06-05 04:36:47
在列表理解版本中,if num not in my_lst总是返回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发布于 2016-06-05 04:41:11
您的条件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)发布于 2016-06-05 04:41:43
或使用集合:
#!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))https://stackoverflow.com/questions/37634691
复制相似问题