Do this as a list comprehension?

Jason Scheirer jason.scheirer at gmail.com
Mon Jun 9 23:20:47 EDT 2008


On Jun 9, 7:06 am, Ricardo Aráoz <ricar... at gmail.com> wrote:
> Mensanator wrote:
> > On Jun 6, 1:40 pm, The Pythonista <n... at this.time> wrote:
> >> On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno 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)
> >> score_costs = [(base_scores[i], score_costs[i]) for i in range (len
> >> (base_scores))]
>
> > What happens if your iterables aren't the same length?
>
> >> But, I'd rather just use zip. :-)
>
> > And with zip() you won't get an error, but it won't be correct,
> > either.
>
> Wouldn't it be nice to have leftZip(), rightZip(), and fullZip() for
> when the lists have different lengths? The final tuples for a leftZip
> could be in the form (value, ) and for right zip (, value) (though I
> think this last tuple is not allowed in python's syntax, we might define
> a "Null" or "Empty" name to act as a place holder in the resulting tuples).

You can go

zip(xrange(9, 10000000000L), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])

since xrange DOES NOT return a list but a constant-memory iterable.

Also, there is itertools for adding default values after you fall off
the end of a list.

>>> import itertools
>>> zip(xrange(100), itertools.chain([0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3], itertools.cycle([None])))

Whose output is:

[(0, 0), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 2), (8,
2), (9, 3), (10, 3), (11, None), (12, None), (13, None), (14, None),
(15, None), (16, None), (17, None), (18, None), (19, None), (20,
None), (21, None), (22, None), (23, None), (24, None), (25, None),
(26, None), (27, None), (28, None), (29, None), (30, None), (31,
None), (32, None), (33, None), (34, None), (35, None), (36, None),
(37, None), (38, None), (39, None), (40, None), (41, None), (42,
None), (43, None), (44, None), (45, None), (46, None), (47, None),
(48, None), (49, None), (50, None), (51, None), (52, None), (53,
None), (54, None), (55, None), (56, None), (57, None), (58, None),
(59, None), (60, None), (61, None), (62, None), (63, None), (64,
None), (65, None), (66, None), (67, None), (68, None), (69, None),
(70, None), (71, None), (72, None), (73, None), (74, None), (75,
None), (76, None), (77, None), (78, None), (79, None), (80, None),
(81, None), (82, None), (83, None), (84, None), (85, None), (86,
None), (87, None), (88, None), (89, None), (90, None), (91, None),
(92, None), (93, None), (94, None), (95, None), (96, None), (97,
None), (98, None), (99, None)]



More information about the Python-list mailing list