Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python的列表理解中使用多个AND条件?_Python_List_List Comprehension - Fatal编程技术网

如何在python的列表理解中使用多个AND条件?

如何在python的列表理解中使用多个AND条件?,python,list,list-comprehension,Python,List,List Comprehension,我有这段代码,它将2个列表作为输入,并打印第3个列表,其中包含这两个列表的公共元素,没有重复项 一种方法是注释for循环,它工作良好,并给出了预期的结果。我试图通过列表理解来实现它,但它会重复 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] c=[] # for i in a: # if i in b and i not in c: # c

我有这段代码,它将2个列表作为输入,并打印第3个列表,其中包含这两个列表的公共元素,没有重复项

一种方法是注释for循环,它工作良好,并给出了预期的结果。我试图通过列表理解来实现它,但它会重复

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c=[]
# for i in a:
#     if i in b and i not in c:
#         c.append(i)

c = [i for i in a if i in b and i not in c ]
print c
预期结果: [1,2,3,5,8,13]

使用列表理解的具有重复项的当前结果: [1,1,2,3,5,8,13]


我使用的是Python2.7

列表在列表中构建时无法查询自身。条件
i not in c
将始终在执行列表comp之前查询
c
(空列表
[]
)的相同值,因此您的代码不知道在下一次迭代中插入了什么


选项1

如果顺序不重要,您可以执行
设置
交叉:

c = set(a) & set(b)
print(list(c))
[1, 2, 3, 5, 8, 13] # Warning! Order not guaranteed

选项2

如果顺序很重要,请使用
for
循环:

c = []
b = set(b)   
for i in a:
     if i in b and i not in c:
         c.append(i)

print(c)
[1, 2, 3, 5, 8, 13]

选项3

由于使用了
OrderedDict
,上述版本的速度稍快一些,可以保留订单:

from collections import OrderedDict

b = set(b)
c = list(OrderedDict.fromkeys([i for i in a if i in b]).keys())
print(c)
[1, 2, 3, 5, 8, 13]

列表在列表中构建时无法查询自身。条件
i not in c
将始终在执行列表comp之前查询
c
(空列表
[]
)的相同值,因此您的代码不知道在下一次迭代中插入了什么


选项1

如果顺序不重要,您可以执行
设置
交叉:

c = set(a) & set(b)
print(list(c))
[1, 2, 3, 5, 8, 13] # Warning! Order not guaranteed

选项2

如果顺序很重要,请使用
for
循环:

c = []
b = set(b)   
for i in a:
     if i in b and i not in c:
         c.append(i)

print(c)
[1, 2, 3, 5, 8, 13]

选项3

由于使用了
OrderedDict
,上述版本的速度稍快一些,可以保留订单:

from collections import OrderedDict

b = set(b)
c = list(OrderedDict.fromkeys([i for i in a if i in b]).keys())
print(c)
[1, 2, 3, 5, 8, 13]