Home > Back-end >  Iterate multiple lists and write down positions of specific repeating elements
Iterate multiple lists and write down positions of specific repeating elements

Time:07-27

Let's say I have multiple lists as follow:

for i in range(len(vera)):
    print(vera[i].numbers)

and output is:

[6 6 7 6 6 6 8 6 7 1 1 1 1 1 1 1 1]
[6 7 6 8 6 6 6 6 6 1 1 1 1 1 1 1 1 1]
[6 6 6 6 6 6 7 8 1 1 1 1 1 1 1 1 1]
[7 6 6 9 6 7 6 8 8 1 1 1]
[7 6 8 8 6 6 6 6 8 1 1 1 1 1 1 1 1 1]
[6 8 6 6 6 6 6 6 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[8 6 6 6 6 6 6 8 1 1 1 1 1 1]

How can I store the positions of each 1 for every list as nested list such as:

[[9, 10, 11, 12, 13, 14, 15, 16], [9, 10, 11, 12, 13, 14, 15, 16], ....]

Many thanks for some suggestions...

CodePudding user response:

You could make use of a double list comprehension to achieve this:

[{position for position,value in enumerate(x.numbers) if value == 1} for x in vera]

Beware that is not good practice to iterate over the range, in this case you only needed the items in the list.

here is a sample code to check my code (the attribute isn't there because it's a list)

vera = [
[6, 6, 7, 6, 6, 6, 8, 6, 7, 1, 1, 1, 1, 1, 1, 1, 1],
[6, 7, 6, 8, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[6, 6, 6, 6, 6, 6, 7, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[7, 6, 6, 9, 6, 7, 6, 8, 8, 1, 1, 1,],
[7, 6, 8, 8, 6, 6, 6, 6, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[6, 8, 6, 6, 6, 6, 6, 6, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[8, 6, 6, 6, 6, 6, 6, 8, 1, 1, 1, 1, 1, 1,],
]
print([{position for position,value in enumerate(x) if value == 1} for x in vera])

Output shown:

[{9, 10, 11, 12, 13, 14, 15, 16}, {9, 10, 11, 12, 13, 14, 15, 16, 17}, {8, 9, 10, 11, 12, 13, 14, 15, 16}, {9, 10, 11}, {9, 10, 11, 12, 13, 14, 15, 16, 17}, {9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}, {8, 9, 10, 11, 12, 13}]

NOTE: i'm using sets because the numbers are unique (and optimizations that comes with sets) this actually doesn't change at all the result without set.

CodePudding user response:

import pandas as pd
[list(pd.Series(l)[pd.Series(l).eq(1)].index) for l in vera]

Output:

[[9, 10, 11, 12, 13, 14, 15, 16],
 [9, 10, 11, 12, 13, 14, 15, 16, 17],
 [8, 9, 10, 11, 12, 13, 14, 15, 16],
 [9, 10, 11],
 [9, 10, 11, 12, 13, 14, 15, 16, 17],
 [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
 [8, 9, 10, 11, 12, 13]]
  • Related