1

I have a list in the form like this

[(x1,y0,output), (x1,y1,output), (x1,y2,output), (x2,y0,output), (x2,y1,output), (x2,y2,output)]

[(1, 0, 0), (1, 1, 1), (1, 2, 2), (2, 0, 0), (2, 1, 2), (2, 2, 4)]

I would like to get cells in the list with a specific condition.

For example,

  1. I want all of the cells which x = 1

    I hope the result is: [(1, 0, 0), (1, 1, 1), (1, 2, 2)]

  2. I want all of the cells which x = 1, y = 2

    I hope the result is: [(1, 2, 2)]

How can I do this?

import numpy as np

result = []
for x in np.arange(1, 3, 1):
    for y in np.arange(0, 3, 1):
        res = y * x
        res = (x, y, res)

        result.append(res)

print(result)

2 Answers 2

2

You could use list comprehension for this. For example, with your given inputs.

>>>[x for x in result if x[0] == 1]
[(1, 0, 0), (1, 1, 1), (1, 2, 2)]
>>>[x for x in result if x[0] == 1 and x[1] == 2]
[(1, 2, 2)]
Sign up to request clarification or add additional context in comments.

2 Comments

How can I get the third value in the cell? For example, the result I get from [x for x in result if x[0] == 1 and x[1] == 2] is [(1, 2, 2)]. How can I get the result only shows the third value -> [2]
@Joanne You could index the x value that's being returned from the iteration. [x[2] for x in result if x[0] == 1 and x[1] == 2] returns [2].
1

Try a list comprehension:

listy = [(1, 0, 0), (1, 1, 1), (1, 2, 2), (2, 0, 0), (2, 1, 2), (2, 2, 4)]
list1 = [e for e in listy if e[0]==1]
list2 = [e for e in listy if e[0]==1 and e[1]==2]

You can change the conditions you choose by in that last if part of the list comprehension.

1 Comment

How can I get the third value in the cell? For example, the result I get from [e for e in result if e[0] == 1 and e[1] == 2] is [(1, 2, 2)]. How can I get the result only shows the third value -> [2]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.