Reputation: 163
I have two list of tuples:
L1 = [(192.168.1.1, name1), (192.168.1.2, name2), (192.168.1.3, name3), (192.168.1.4, name4)]
L2 = [(192.168.1.1, data1, data2), (192.168.1.2, data3, data4)]
L1 has all possible ip/names that can occur, while L2 has currently active ip and its data.
My objective is to get one list, let's call it L3, which needs to have ip and name from L1 and data from L2 for all elements in L2.
L3 = [(192.168.1.1, name1, data1, data2), (192.168.1.2, name2, data3, data4)]
Solution I came up after giving up on list comprehension is really dirty, and probably slow. I haven't tested it yet on bigger data set, but speed will be important, so I need your help guys. I would like this to be done with list comprehension for speed and for the sake of learning something new. Thanks in advance.
My dirty solution:
L3=[]
for item in L1:
for i in range(len(L2)):
if L2[i][0] == item[0]:
L3.append((item[0], item[1], L2[i][1], L2[i][2]))
Upvotes: 1
Views: 48
Reputation: 174706
Use list comprehension.
>>> L1 = [('192.168.1.1', 'foo'), ('192.168.1.2', 'bar'), ('192.168.1.3', 'buzz')]
>>> L2 = [('192.168.1.1', 'data1', 'data2'), ('192.168.1.2', 'data3', 'data4')]
>>> [j + i[1:] for i in L2 for j in L1 if j[0] == i[0]]
[('192.168.1.1', 'foo', 'data1', 'data2'), ('192.168.1.2', 'bar', 'data3', 'data4')]
Upvotes: 4