nested tuple slice
Brian van den Broek
bvande at po-box.mcgill.ca
Tue Apr 12 18:28:24 EDT 2005
dimitri pater said unto the world upon 2005-04-12 17:49:
> hello!
>
> I want to change a nested tuple like:
> tuple = (('goat', 90, 100), ('cat', 80, 80), ('platypus', 60, 800))
> into:
> tuple = (('goat', 90), ('cat', 80), ('platypus', 60))
>
> in other words, slice the first elements of every index
>
> Any ideas on how to do this in an elegant, pythonic way?
>
> Best regards,
> Dimitri
>
>
Hi Dimitri,
here's one way:
>>> my_tuple = (('goat', 90, 100), ('cat', 80, 80), ('platypus', 60,
800))
>>> my_sliced_tuple = tuple([x[0:2] for x in my_tuple])
>>> my_sliced_tuple
(('goat', 90), ('cat', 80), ('platypus', 60))
>>>
BTW, don't use `tuple' as a name. You can, but then you hide the
built-in tuple function. And, you need that :-)
Best,
Brian vdB
More information about the Python-list
mailing list