如何在Python中打印两个列表之间的唯一列表元素(也称为如何打印不在两个列表中的项目)

2024-05-16 00:16:41 发布

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

编写一个将两个列表作为参数的函数。您的函数应该检查两个列表中是否都有一个元素。检查所有元素后,函数应打印以下内容:

这些项目都在两个列表中:(两个列表中的元素)我把这个项目做对了

这些项目不在两个列表中:(不在两个列表中的元素)这是我需要帮助的项目

例如,给定

listOne = ["a", "b", "c", "d"]listTwo = ["c", "d", "e", "f"]

您的函数将打印

这些项目都在两个列表中:c和d 这些项目不在两个列表中:a b e f

使用以下函数标题:

def checkItemsInList(listOne, listTwo):

下面是我最后得到的代码,对于两个列表中的项目,我正确地得到了该部分,,但是对于请求不在两个列表中的项目的部分,当我需要['a','b','e','f']时,我得到了错误的['b', 'a']输出

INPUT
    def checkItemsInList(listOne, listTwo):
        listOne = ["a", "b", "c", "d"]
        listTwo = ["c", "d", "e", "f"]

# for the items in both lists
print(list(set(listOne) & set(listTwo)))
# for the items not in both lists
list(set(listOne) - set(listTwo))

OUTPUT
['d', 'c']
['b', 'a']

Tags: the项目函数in元素列表fordef
3条回答

检查这个是否有效

def checkItemsInList(listOne, listTwo):
    res = []
    for i in listOne:
        if i in listTwo:
            res.append(i)
    print(res)

对于其余图元,可以使用

list(set(listOne) ^ set(listTwo))

您没有检查列表_b中存在但不在列表_a中的项目(您只检查了相反方向):

in_both = list(set(listOne) & set(listTwo))
# for the items not in both lists
not_in_both = list(set(listOne) - set(listTwo)) + list(set(listTwo) - set(listOne))

not_in_both = list(set(listOne+listTwo)-set(in_both))

您可以使用函数对称性

>>> set(listOne).symmetric_difference(listTwo)
{'b', 'f', 'e', 'a'}

相关问题 更多 >