[英]Comparing two lists in Python
因此,举一个粗略的例子,还没有为它编写任何代码,我很好奇我如何能够找出这两个列表的共同点。
例子:
listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']
我希望能够返回:
['a', 'c']
为何如此?
可能带有可变字符串,例如:
john = 'I love yellow and green'
mary = 'I love yellow and red'
并返回:
'I love yellow and'
为此使用设置交集:
list(set(listA) & set(listB))
给出:
['a', 'c']
请注意,由于我们正在处理集合,因此可能无法保持顺序:
' '.join(list(set(john.split()) & set(mary.split())))
'I and love yellow'
使用join()
将结果列表转换为字符串。
——
对于下面的示例/评论,这将保留顺序(灵感来自@DSM 的评论)
' '.join([j for j, m in zip(john.split(), mary.split()) if j==m])
'I love yellow and'
对于列表长度不同的情况,结果如以下注释中所指定:
aa = ['a', 'b', 'c']
bb = ['c', 'b', 'd', 'a']
[a for a, b in zip(aa, bb) if a==b]
['b']
如果两个列表的长度相同,则可以进行并排迭代,如下所示:
list_common = []
for a, b in zip(list_a, list_b):
if a == b:
list_common.append(a)
将它们作为集合相交:
set(listA) & set(listB)
我想这就是你想问我的任何关于它的问题我会尽量回答它
listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']
new1=[]
for a in listA:
if a in listB:
new1.append(a)
john = 'I love yellow and green'
mary = 'I love yellow and red'
j=john.split()
m=mary.split()
new2 = []
for a in j:
if a in m:
new2.append(a)
x = " ".join(new2)
print(x)
如果顺序无关紧要,但您想打印出一个不错的差异:
def diff(a, b):
if len(set(a) - set(b)) > 0:
print(f"Items removed: {set(a) - set(b)}")
if len(set(b) - set(a)) > 0:
print(f"Items added: {set(b) - set(a)}")
if set(a) == set(b):
print(f"They are the same")
diff([1,2,3,4], [1,2,3])
# Items removed: {4}
diff([3,4], [1,2,3])
# Items removed: {4}
# Items added: {1, 2}
diff([], [1,2,3])
# Items added: {1, 2, 3}
diff([1,2,3], [1])
# Items removed: {2, 3}
listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']
diff(listA, listB)
# Items removed: {'b'}
# Items added: {'h'}
john = 'I love yellow and green'
mary = 'I love yellow and red'
diff(john, mary)
# Items removed: {'g'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.