0

Possible Duplicate:
Finding the index of a list in a loop

Assume you have a list, where not just the values have meaning, the index has, too.

counts = [3,4,5,3,1]

Let's say that means "we have 3 objects of type zero, 4 objects of type 1 and so on".

You want to create a list of objects from that and give these objects both information details:

[CountObject(amount=a,type=???) for a in counts]

How would you do that?

0

3 Answers 3

7

Use the enumerate() function:

[CountObject(amount=a, type=i) for i, a in enumerate(counts)]

where i is then the index.

Sign up to request clarification or add additional context in comments.

2 Comments

As an aside for anyone who may need this in the future: if there are several lists (say counts and averages for instance), and you also need the index, use zip and itertools.count to avoid nested tuple unpacking: for i, c, a in zip(count(), counts, averages).
@lazyr: That deserves a new question post with self-answer!
1

Something like:

[CountObject(amount=counts[a],type=a) for a in range(len(counts))]

would do what you want i guess .

1 Comment

Yeah, but it's one of the things that is discouraged in Python.
1

beside enumerate() you can also try range(), use xrange() if you're on python 2.x:

[CountObject(amount=counts[i],type=i) for i in range(len(counts))]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.