[[+content_image]]
A
A
Alexander Rublev2018-04-04 15:41:20
Python
Alexander Rublev, 2018-04-04 15:41:20

How to join lists by condition?

Hello! I can't find a nice way to join 2 lists.
There are 2 lists (lists have 15000+ sublists):

a = [[1, 100], [2, 200], [3,300], ...]
b = [[1, 110],  [3,330], ...]

At the output, I need to combine them by the first element of each list Or you can combine them into a dictionary. How to do it beautifully in Python? And what would it be fast)
с = [[1, 100, 110], [2, 200], [3, 300, 310], ...]

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
DDDsa, 2018-04-04
@Meller008

a = [[i, i*100] for i in range(15000)]
b = [[i, i*110] for i in range(15000)]
c = {}

for i in a+b:
    c.setdefault(i[0], []).append(i[1:])

For example?
UPD: from the point of view of wasting resources, it is probably more correct to make two loops instead, for a and for b. This way we won't allocate memory for a new useless list just to make the code look more concise. But 15,000 sublists is, in general, nonsense and you shouldn’t bother too much. for i in a+b

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question