Home > Blockchain >  Enumerate and get the first item of each tuple?
Enumerate and get the first item of each tuple?

Time:01-07

How to get from this:

col = [('red', '132', '234'), ('green', '236', '434'), ('brown', '542', '457')]

to this:
EDIT (without any quotes)

1 red, 2 green, 3 brown   # enumerate and get the first item of each tuple.

I tried this, but it doesn't work:

[zip(((enumerate(col),1),i[0])) for i in col]

Only built-in functions please.

CodePudding user response:

You can use list comprehension.

>>> col = [('red', '132', '234'), ('green', '236', '434'), ('brown', '542', '457')]
>>>
>>> ["{} {}".format(index, first) for index, (first, *_) in enumerate(col, start=1)]
['1 red', '2 green', '3 brown']

CodePudding user response:

First use enumerate with an appropriate starting value. Next, unpack the resulting tuple to get just the values you need. Finally, use an f-string to create the desired string from the number and the color name.

[f"{i} {color}" for i, (color, _, _) in enumerate(col, 1)]

CodePudding user response:

print([f"{i   1} {each[0]}" for i, each in enumerate(col)])
  •  Tags:  
  • Related