Home > OS >  How can I assign non-numerical Ids?
How can I assign non-numerical Ids?

Time:08-12

I have a list of Strings and I want to assign to all of them a unique suffix as an Id as it follows:

Let's asume that the list is ["str1", "str2", "str3"], I want to insert the Ids like this: ["str1-a", "str2-b", "str3-c"].

Is there any way of assigning these ids iteratively like:

id = a
for each element in the list:
    add the id to the string
    increment the id # from a to b, from b to c etc.

instead of getting each element in order and doing it three times?

Thanks!!

CodePudding user response:

There is a constant in the string module which has all the letters in a string, like 'abcdefg...'. See the docs.

from string import ascii_lowercase
new_list = []
for letter, element in zip(ascii_lowercase, old_list):
    new_list.append(element   '-'   letter)

Or, using a list comprehension:

new_list = [element   '-'   letter for letter, element in zip(ascii_lowercase, old_list)]
  • Related