Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I assign non-numerical Ids?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!!

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading