Home > Net >  How to replace all list of list items with the index value of that list
How to replace all list of list items with the index value of that list

Time:11-27

I am trying to replace items in list of lists by the value of the index of that specific list. I can do it with a for loop, but I was wondering if there is a faster way to do this.

such that the following list

example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

becomes:

solution = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]

CodePudding user response:

Your way with for loop should work, but if you want another way in a short version then you can do it this way with list comprehension and enumerate,

example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [[index] * len(value) for index, value in enumerate(example)]
print(result)

CodePudding user response:

List comprehensions are usually faster than loops

Here is a solution with list comprehensions

example = [[1,2,3],[4,5,6],[7,8,9]]
solution = [[x for _ in range(len(example[x]))] for x in range(len(example))]
print(solution)
Output
[[0, 0, 0], [1, 1, 1], [2, 2, 2]]

CodePudding user response:

solution = [[i]*len(x) for i, x in enumerate(example)]

CodePudding user response:

Here is a solution with the map function:

res = list(map(lambda i : [i] * len(example[i]),
            range(len(example))
        ))
print(res)

It's more verbose than the comprehension method, but coming from other languages I prefer it - I find the map to be more explicit and easier to follow, as it's built out of the common components of higher-order functions rather than having its own syntax.

  • Related