0

i have two value:starid1,starid2,and a list called starlist, i want to pick up two object from the starlist that contains id starid1 and starid2,and there is no duplicated id in the list.

this is how i write the code

star1,star2=None,None
for x in starlist:
    if x.id == starid1:
        star1 = x
    elif x.id == starid2:
        star2 = x

here's another way

star1 = [x for x in starlist if x.id==starid1][0]
star2 = [x for x in starlist if x.id==starid2][0]

or i can convert it to a dictionary and pick the two objects.but i thought the cost was too high, for i only want to assign two values.

i felt so dumb when i wrote those codes down.i think i just missed the proper way to do it in python. tell me how you know to do it better.

1
  • Can you provide some sample data, and an example of the output? Commented Jan 23, 2013 at 11:54

1 Answer 1

3

A common way is to use a generator:

star1 = next(x for x in starlist if x.id==starid1)
star2 = next(x for x in starlist if x.id==starid2)

This has an advantage of being lazy thus saving memory and stopping early. In your example, this is basically the same as your first loop with break statements added to it:

star1,star2=None,None

for x in starlist:
    if x.id == starid1:
       star1 = x
       break

for x in starlist:
    if x.id == starid2:
       star2 = x
       break

Do note however, that next will raise an exception if there's no such item in the list. If you want to avoid that, add a default value to the call:

star1 = next((x for x in starlist if x.id==starid1), None)
Sign up to request clarification or add additional context in comments.

2 Comments

Your loop would break after the first star is found, a better check would be if star1 and star2: break
Sorry, using a generator like that is not a common way to do it.

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.