Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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中比较两个列表,并在一个列表中写入相似的索引值,在另一个列表中写入不相似的值_Python_Python 3.x_List_String Comparison - Fatal编程技术网

如何在python中比较两个列表,并在一个列表中写入相似的索引值,在另一个列表中写入不相似的值

如何在python中比较两个列表,并在一个列表中写入相似的索引值,在另一个列表中写入不相似的值,python,python-3.x,list,string-comparison,Python,Python 3.x,List,String Comparison,考虑两个列表 a=[1,2,3],b=[1,4,5]。代码应该打印类似的值c=[1],代码应该打印显示不同值的d=[2,3,4,5] --已完成--您可以为此使用集合 a = [1,2,3] b = [1,4,5] c = list(set(a).intersection(b)) d = list(set(a).difference(b)) + list(set(b).difference(a)) intersection查找公共元素,而difference查找不同的元素。您必须以两种方式执

考虑两个列表 a=[1,2,3],b=[1,4,5]。代码应该打印类似的值c=[1],代码应该打印显示不同值的d=[2,3,4,5]


--已完成--

您可以为此使用集合

a = [1,2,3]
b = [1,4,5]

c = list(set(a).intersection(b))
d = list(set(a).difference(b)) + list(set(b).difference(a))

intersection
查找公共元素,而
difference
查找不同的元素。您必须以两种方式执行此操作,因为
差异
运算符基本上只显示第一个集合中不在第二个集合中的元素。

下面给出了使用和逻辑运算符的简单替代解决方案:

a = [1,2,3]
b = [1,4,5]

print([x for x in a if x in b])
print([x for x in set(a+b) if (x in a) ^ (x in b)])

另一个人已经给出了一个设置操作的解决方案,所以我不再重复了。

@vicrobot:你能帮我解决你的问题吗?当你试图解决这个问题时,你在哪里卡住了?