Combining two Python lists

I would like to combine the two lists based on the identifier in table 2 displayed in table 1.

table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),
          (u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]

Combined = [item for item in table2 if item[0] in table1]
print Combined

Results:

[]

Desired Results:

[(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim')]
+4
source share
6 answers

Your problem is here:

if item[0] in table1

Instead, you should compare item[0]which is the first element of the tuple with the first element in table1.

if item[0] in [elment[0] for element in table1]
+2
source

ok fine

table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
#convert to dictionaries (a more appropriate data structure,imho at least)
dict1=dict(table1)
dict2=dict((item[0],item[1:]) for item in table2)
#get the intersection
final = dict((key,dict2[key]+(dict1[key],)) for key in set(dict1).intersection(dict2))
print final

you will probably see a significant increase in speed if your tables are large

+3
source

, , :

Combined = []
for entry1 in table1:
  for entry2 in table2:
    if entry1[0]==entry2[0]:
      Combined.append(entry2)
print Combined
+1

if item[0] in table1 , , u'Id1' u'Id2' table1. table1 - , , . , str == tuple False.

, :

>>> table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
>>> table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
>>> ids = [x[0] for x in table1]
>>> Combined = [item for item in table2 if item[0] in ids]
>>> Combined
[('Id1', 'Proudct1', None, 'New', 'Id#343', 'Jim')]
>>>

ids id, table1:

>>> table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
>>> ids = [x[0] for x in table1]
>>> ids
['Id1', 'Id4']
>>>

, if item[0] in table1 , item[0] .


, in O(n) () ids table2. . :

ids = {x[0] for x in table1}

O(1) () in, .

0

2, , comb_list .

table1 = [(u'Id1', u'New'), (u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),
          (u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim'),
          (u'Id4', u'Proudct4', None, u'New', u'Id#44444', u'Jim')]

comined_list = []
for i in table1:
    for j in table2:
        if i[0] == j[0]:
            comined_list.append(j)
print comined_list

:

[(u'Id1 ', u'Proudct1', None, u'New ', u'Id # 343', u'Jim '), (u'Id4', u'Proudct4 ', None, u' New ', u'Id # 44444 ', u'Jim')]

0
source
table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
st = {a for b in table1 for a in b}
print([x for x in table2 if x[0] in st])
[(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim')]
0
source

All Articles