0

I have list of bonds between points (as pairs of indexes) and index of a pivot point. I want to list of points bonded to that pivot point irrespective if it is on the first or the second position (I always want the index of the second point to which pivot is bonded in pair).

bonds = [(1,2),(3,4),(5,6),(3,1)]
ipiv  = 1 

bonded_to_pivot = 
[ b[1] for b in bonds if(b[0]==ipiv) ] + 
[ b[0] for b in bonds if(b[1]==ipiv) ] 

Can this be done using just one list comprehension in elegant way?

I was looking into these other question about comprehension with conditional expression but I miss something (e.g. else pass) to make it work

Prokop Hapala
  • 2,424
  • 2
  • 30
  • 59

1 Answers1

1

Assuming you want the coordinate which doesn't match ipiv, try:

>>> [b[1] if b[0]==ipiv else b[0] for b in bonds if ipiv in b]
[2, 3]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • aha, so `if ipiv in b` is evaluated first and than for those which pass that filter we branch between `b[0]==ipiv` and `b[1]==ipiv` . I was really confused about having condition either before or behind the for loop – Prokop Hapala Jul 14 '23 at 14:15