比较两个列表以找到公共元素,然后使用python将其排序为三个不同的列表

2024-10-02 14:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习编写代码,尤其是python。但我的任务是像excel中那样获取两个列表,并找到这两个列表的公共元素。然后在一个单独的电子表格中,列出一列中的公共元素称为this list(相同),列出第一个列表中剩下的元素称为this col1(onlycol1),列出第二个列表中剩下的元素称为this col2(onlycol2)。你知道吗

我的示例列表如下:

col1                  

 1. apple           
 2. banana 
 3. pear
 4. kiwi

col2

 1. apple 
 2. orange 
 3. grapes

列表应该这样排序

same

 1. apple

onlycol1

 1. banana
 2. pear
 3. kiwi

onlycol2

 1. orange 
 2. grapes



col1= [apple, banana, pear, kiwi]
col2= [apple, orange, grapes]

set(col1) & set(col2)

Tags: 代码元素apple列表thiscol2col1banana
1条回答
网友
1楼 · 发布于 2024-10-02 14:27:55

处理这个问题的最佳方法是使用内置的python集。为了获得公共元素,可以使用交集。而要得到只存在于一列中的结果,则要执行减号运算,就像我们在数学中学习集合一样。你知道吗

col1 = ['apple','banana','pear','kiwi']
col2 = ['apple','orange','grapes']

common = list(set(col1)& set(col2))

onlyCol1 = list(set(col1) - set(common))
onlyCol2 = list(set(col2) - set(common))

相关问题 更多 >