Comparing Multiple Lists Python -


i'm trying compare multiple lists. lists aren't label...normally. i'm using while loop make new list each time , label them accordingly. example, if while loop runs 3 times make list1 list2 , list3. here snippet of code create list.

for link in links:     print('*', link.text)     locals()['list{}'.format(str(i))].append(link.text) 

so want compare each list strings in them want compare lists @ once print out common strings.

i feel i'll using this, i'm not 100% sure.

lists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10] common = list(set().union(*lists).intersection(keyword)) 

rather directly modifying locals() (generally not idea), use defaultdict container. data structure allows create new key-value pairs on fly rather relying on method sure lead nameerror @ point.

from collections import defaultdict  = ...  link_lists = defaultdict(list) link in links:     print('*', link.text)     link_lists[i].append(link.text) 

to find intersection of of lists:

all_lists = list(link_lists.values()) common_links = set(all_lists[0]).intersection(*all_lists[1:]) 

in python 2.6+, can pass multiple iterables set.intersection. star-args here.


here's example of how intersection work:

>>> collections import defaultdict >>> c = defaultdict(list) >>> c[9].append("a") >>> c[0].append("b") >>> = list(c.values()) >>> set(all[0]).intersection(*all[1:]) set() >>> c[0].append("a") >>> = list(c.values()) >>> set(all[0]).intersection(*all[1:]) {'a'} 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -