Home > Net >  Find all row index numbers that have the same value in Python
Find all row index numbers that have the same value in Python

Time:03-18

Imagine 2 lists

x_test = [1, 3]
y_test = [1, 1, 3, 2, 2, 3, 1]

From this data I would like to make 2 new lists. The entries of the new lists shall be the row indexes of y_test, when their values = x_test(0) or x_test(1).

Desired Output:
z_1 = [0,1,6]
z_3 = [2,4]

How do I have to change my code in order to receive the desired output?

z_1 = []
for value in enumerate(x_test):
    if value in y_test == x_test[0]:
        z_1.append([index])
print(z_1)

z_3 = []
for value in enumerate(x_test):
    if value in y_test == x_test[1]:
        z_3.append([index])
print(z_1)

CodePudding user response:

You need to iterate on y_test and compare the value with value in x : value == x_test[0]

z_1 = []
for index, value in enumerate(y_test):
    if value == x_test[0]:
        z_1.append(index)
print(z_1)

Generify

result = []
for xvalue in x_test:
    subresult = []
    for index, value in enumerate(y_test):
        if value == xvalue:
            subresult.append(index)
    result.append(subresult)
print(result)  # [[0, 1, 6], [2, 5]]

With list comprehension

result = [[i for i, v in enumerate(y_test) if v == xvalue]
          for xvalue in x_test]

CodePudding user response:

Your approach(using a for loop) seems fine but with a few mistakes (which are mentioned well by @azro). But you can also use list comprehensions:

z_1 = [i for i,y in enumerate(y_test) if y == x_test[0]]
z_3 = [i for i,y in enumerate(y_test) if y == x_test[1]]
print(z_1)
print(z_3)

Output

[0, 1, 6]
[2, 5]

Note that, z_3 should not result in [2, 4] as you mentioned. Rather it should be [2, 5].

  • Related