<分区>
我有两个列表,例如:
a = ['hello','world']
b = ['hello','world','im','steve']
如果我想创建第三个列表,它只包含不在两者中的元素:
c = ['im','steve']
如果元素的顺序很重要,我该怎么做?我知道我可以使用集合,但它们总是打乱我列表的顺序。我可以使用 ' '.join(list)
将它们转换为字符串,但也不确定如何以该格式执行此操作。
标签 python python-3.x
<分区>
我有两个列表,例如:
a = ['hello','world']
b = ['hello','world','im','steve']
如果我想创建第三个列表,它只包含不在两者中的元素:
c = ['im','steve']
如果元素的顺序很重要,我该怎么做?我知道我可以使用集合,但它们总是打乱我列表的顺序。我可以使用 ' '.join(list)
将它们转换为字符串,但也不确定如何以该格式执行此操作。
最佳答案
您可以连接列表并使用列表理解:
a = ['hello','world']
b = ['hello','world','im','steve']
final_vals = [i for i in a+b if i not in a or i not in b]
输出:
['im', 'steve']
关于python - 如何在 Python 中对两个列表进行异或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47985297/