Using enumerate() to enumerate items with letters rather than numbers

Viewed 334

I'm trying to use the built-in function enumerate() to label some points or vertices where each point is represented by its coordinates in a list(or set) of tuples which essentially looks like {(4,5), (6,8), (1,2)}

I want to assign a letter starting from "a" in ascending order to each tuple in this set, using enumerate() does exactly the same but It's written in a way that it returns the value of the index of each item so that it's a number starting from 0.

is there any way to do it other than writing my own enumerate()?

4 Answers

Check this out:

import string
tup = {(4,5), (6,8), (1,2)}
dic = {i: j for i, j in zip(string.ascii_lowercase, tup)}

This returns:

{'a': (4, 5), 'b': (6, 8), 'c': (1, 2)}

This is enumerate's signature.

enumerate(iterable, start=0)

Use start as 65 for 'A' and 97 for 'a'.

lst=[(1,2),(2,3),(3,4),...]
for idx,val in enumerate(lst,65):
    print(chr(idx),val)

A (1, 2)
B (2, 3)
C (3, 4)

Maybe this is a way to get what you want, using chr():

L = [(4,5), (6,8), (1,2)]
for k, v in enumerate(L):
    print(chr(65 + k), v)

Output :

A (4, 5)
B (6, 8)
C (1, 2)

The enumerate function is defined as follow :

enumerate(iterable, start=0)

I think just have to write your own enumerate or an wrapper around enumerate.

Related