Commoner
Commoner

Reputation: 1768

Python: Compare list with its indices and create a new list

In Python, I want to compare a list of lists (say LL1) with the indices of its lists and create another list of lists (say LL2) in such a manner than LL2 has the same exact shape as LL1. As we can see, the list LL1 is inhomogeneous. For example:

LL1 = [[0, 1, 3, 6, 7], [3, 7], [0, 1, 2, 6, 7], [3], [0, 3, 4, 5, 8]]
LL2 = [[0, 0, 0, 0, 0], [1, 1], [2, 2, 2, 2, 2], [3], [4, 4, 4, 4, 4]]

I want to achieve this in the fastest way possible. Presently, I am using the following method:

MP = map(len, LL1)
LL2 = map( lambda x: MP[x]*[x] , range(len(LL1)) )

For large datasets, the second step is not very fast. Is there a faster alternative to what I am doing? I will really appreciate any help.

Upvotes: 1

Views: 44

Answers (2)

McGrady
McGrady

Reputation: 11487

Try this:

print([ [LL1.index(i)] * len(i) for i in LL1])

Output:

[[0, 0, 0, 0, 0], [1, 1], [2, 2, 2, 2, 2], [3], [4, 4, 4, 4, 4]]

Maybe the above code is not good enough when you got many duplicate elements,so you can try this:

print([[i]*len(j) for i,j in enumerate(LL1)])

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96172

You can use a list-comprehension to do this in one step:

>>> LL1 = [[0, 1, 3, 6, 7], [3, 7], [0, 1, 2, 6, 7], [3], [0, 3, 4, 5, 8]]
>>> LL2 = [[i]*len(sub) for i, sub in enumerate(LL1)]
>>> LL2
[[0, 0, 0, 0, 0], [1, 1], [2, 2, 2, 2, 2], [3], [4, 4, 4, 4, 4]]
>>>

Another way:

>>> LL2 = [[i for _ in range(len(sub))] for i, sub in enumerate(LL1)]
>>> LL2
[[0, 0, 0, 0, 0], [1, 1], [2, 2, 2, 2, 2], [3], [4, 4, 4, 4, 4]]
>>>

Not sure which is faster...

Upvotes: 2

Related Questions