Do this as a list comprehension?
Terry Reedy
tjreedy at udel.edu
Fri Jun 6 02:44:52 EDT 2008
"Mensanator" <mensanator at aol.com> wrote in message
news:bbd90051-36be-4378-9a27-2a47a5471d12 at a1g2000hsb.googlegroups.com...
| On Jun 5, 10:42?pm, John Salerno <johnj... at gmailNOSPAM.com> wrote:
| > Is it possible to write a list comprehension for this so as to produce
a
| > list of two-item tuples?
| >
| > base_scores = range(8, 19)
| > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
| > print zip(base_scores, score_costs)
| >
| > I can't think of how the structure of the list comprehension would work
| > in this case, because it seems to require iteration over two separate
| > sequences to produce each item in the tuple.
Which is exactly the purpose of zip, or its specialization enumerate!
| > zip seems to work fine anyway, but my immediate instinct was to try a
| > list comprehension (until I couldn't figure out how!). And I wasn't
sure
| > if list comps were capable of doing everything a zip could do.
|
| base_scores = range(8, 19)
| score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
| print zip(base_scores, score_costs)
|
| s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])]
| print s
|
| ##>>>
| ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
| 2), (16, 2), (17, 3), (18, 3)]
| ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
| 2), (16, 2), (17, 3), (18, 3)]
| ##>>>
Of course, enumerate(iterable) is just a facade over zip(itertools.count(),
iterable)
More information about the Python-list
mailing list