在Python中比较两个列表 [英] Comparing two lists in Python

查看:124
本文介绍了在Python中比较两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了给出一个粗略的例子,没有为它编写任何代码,我很好奇,我将能够找出这两个列表有共同点。

So to give a rough example without any code written for it yet, I'm curious on how I would be able to figure out what both lists have in common.

示例:

listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']

['a', 'c']

如何?

可能使用以下变量字符串:

Possibly with variable strings like:

john = 'I love yellow and green'
mary = 'I love yellow and red'

并返回:

'I love yellow and'


推荐答案

对此使用集交集:

list(set(listA) & set(listB))


b $ b

提供:

gives:

['a', 'c']

请注意,由于我们正在处理集合,所以 p>

Note that since we are dealing with sets this may not preserve order:

' '.join(list(set(john.split()) & set(mary.split())))
'I and love yellow'

join()将结果列表转换为字符串。

using join() to convert the resulting list into a string.

-

对于您的示例/注释,此将保留顺序(受@DSM的评论启发)

For your example/comment below, this will preserve order (inspired by comment from @DSM)

' '.join([j for j, m in zip(john.split(), mary.split()) if j==m])
'I love yellow and'

对于列表长度不同的情况,

For a case where the list aren't the same length, with the result as specified in the comment below:

aa = ['a', 'b', 'c']
bb = ['c', 'b', 'd', 'a']

[a for a, b in zip(aa, bb) if a==b]
['b']

这篇关于在Python中比较两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆