开发者

Python how to iterate through a list and compare lists of strings found within

开发者 https://www.devze.com 2023-01-24 05:53 出处:网络
If I have a nested list that looks like this: bigstringlist = [[\'rob\', \'bob\', \'sam\', \'angie\'], [\'jim\', \'angie\', \'tom\', \'sam\'], [\'sam\', \'mary\', \'angie\', \'sally\']]

If I have a nested list that looks like this:

bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]

How do I iterate through this list and extract a list of names that appear in all the nest开发者_如何学JAVAed lists? i.e.:

finallist = ['sam', 'angie']

Would this be better accomplished by typecasting this nested list as a set?


reduce(set.intersection, map(set , bigstringlist))


A variation on singularity's solution, maybe a little faster:

bigstringiter = iter(bigstringlist)
reduce(set.intersection, bigstringiter, set(next(bigstringiter)))
0

精彩评论

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

关注公众号