kauray
kauray

Reputation: 719

How to group a list according to another list in which each element is a list of values?

I have two equal length lists

x = [1,[2],3] 
y=[[7],[8,9],[8,9]]

I would like to group the first list according to the second list. That is, the group should be the same for the x = 2,3 since the corresponding y lists is the same. The grouping should thus yield

[[1], [[2],3]]

What is the simplest way to achieve this?

Upvotes: 0

Views: 151

Answers (3)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

Use := could do list comprehension in Python 3.8:

x = [1, [2], 3]
y = [[7], [8, 9], [8, 9]]


a = iter(x)
z = [[tmp for j in range(len(i)) if (tmp := next(a, None))] for i in y]
# [[1], [[2], 3], []]
output = [i for i in z if i] # remove [] in the list.
# [[1], [[2], 3]]

Upvotes: 2

ywbaek
ywbaek

Reputation: 3031

I think the simplest way to do it is using a dictionary.
You can use string representation of y elements as keys
and associated x elements as values:

x = [1, [2], 3]
y = [[7], [8, 9], [8, 9]]

d = {}
for k, v in zip(y, x):
    if str(k) in d:
        d[str(k)].append(v)
    else:
        d[str(k)] = [v]

print(list(d.values()))
[[1], [[2], 3]]

Upvotes: 2

Dominic D
Dominic D

Reputation: 1808

x = [1,2,3]
y = [[7],[8,9],[8,9]]

output = []
values = []
for i, v in zip(x,y):
    if v in values:
        output[values.index(v)].append(i)
    else:
        output.append([i])
    values.append(v)

Upvotes: 2

Related Questions