开发者

How to get a list with elements that are contained in two other lists?

We have two lists:

a=['开发者_StackOverflow社区1','2','3','4']
b=['2','3','4','5']

How to get a list with elements that are contained in both lists:

a_and_b=['2','3','4']

and a list with elements that are contained only in one list, but not the other:

only_a=['1']
only_b=['5']

Yes, I can use cycles, but it's lame =)


if order is not important

>>> a=['1','2','3','4']
>>> b=['2','3','4','5']
>>> set(a) & set(b)
set(['3', '2', '4'])

only a

>>> set(a).difference(b) # or set(a) - set(b)
set(['1'])

only b

>>> set(b).difference(a)  # or set(b) - set(a)
set(['5'])


Simply with the use of sets:

>>> a=['1','2','3','4']; b=['2','3','4','5']
>>> a = set(a)
>>> b = set(b)
>>> a & b
set(['3', '2', '4'])
>>> a - b
set(['1'])
>>> b - a
set(['5'])
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜