Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

python - How to find common elements in list of lists?

I'm trying to figure out how to compare an n number of lists to find the common elements. For example:

p=[ [1,2,3],
    [1,9,9],
      ..
      ..
    [1,2,4]

>> print common(p)
>> [1]

Now if I know the number of elements I can do comparions like:

for a in b:
  for c in d:
    for x in y:
...

but that wont work if I don't know how many elements p has. I've looked at this solution that compares two lists https://stackoverflow.com/a/1388864/1320800

but after spending 4 hrs trying to figure a way to make that recursive, a solution still eludes me so any help would be highly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking for the set intersection of all the sublists, and the data type you should use for set operations is a set:

result = set(p[0])
for s in p[1:]:
    result.intersection_update(s)
print result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...