-2

Hello guys I have list like A

max_x=4

min_x=0

A=[[(0, 1), (1, 0), (1, 1), (2, 0)], [(0, 3), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2)]]

A, includes different group of points (x,y) format.I wanted to find group if includes my max and min same time.Output should be like B.Because this cluster includes 0 and 4 as x.

B= [(0, 3), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2)]

Thank you.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
randint00
  • 5
  • 1
  • Welcome to Stack Overflow. My advice is to try to break the problem down into smaller parts. For example, if you had a single list from A, could you write code that tells you whether it meets the condition? If that's too hard, break it down again - consider one of the tuples, like `(0, 3)`. Can you write code to tell if includes the max X value? Now, think about how to repeat that test, and check whether *any* of the tuples meets the condition. Then use that code with the `max_x` and `min_x` values, to see if *both* are found. Then use *that* code to test each `A` value separately. – Karl Knechtel May 28 '22 at 00:28
  • Each of those broken-down steps offers you a separate question, and a separate place to learn technique for solving problems. As a side note: this question clearly doesn't have anything to do with Numpy, so I removed that tag. – Karl Knechtel May 28 '22 at 00:29

1 Answers1

1

You could use a list comprehension to find any sublists of A that have a tuple that has x == min_x and also a tuple that has x == max_x:

max_x=4
min_x=0
A=[[(0, 1), (1, 0), (1, 1), (2, 0)], [(0, 3), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2)]]

B = [l for l in A if any(x == min_x for x,_ in l) and any(x == max_x for x,_ in l)]

Output:

[[(0, 3), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2)]]
Nick
  • 138,499
  • 22
  • 57
  • 95
  • when I use this code for my A it prints same as A. My output not seems like B.Thank you. – randint00 May 28 '22 at 01:33
  • I'm using the same data as in your question and I get the result I show in the answer. See for example https://ideone.com/ZdA44i – Nick May 28 '22 at 01:37
  • Could it be that, for the actual `A`, every element *actually does* meet the condition? – Karl Knechtel May 28 '22 at 01:51
  • @KarlKnechtel assuming the code from the answer, that would seem to be the only solution – Nick May 28 '22 at 01:53