S.Web S.Web - 1 year ago 45
Python Question

How can I assign each item in a list a seperate number, and then print these numbers as a string? - Python

please bear with me as I'm rather new to python.

I would like to take a string of a few words, change this to a list, and give each item in the list an individual number (i guess you call it an index). I've looked around for solutions and seen the enumerate function mentioned often. I am able to use it, but what i would like to do is assign the duplicate words in the string the same index as the one before it. I have no clue how to accomplish this!

For example, if the string was "How does one do this How does one do this", the numbers would read "1234512345" - the word "How" is assigned 1, and "does" 2 etc.

Any help is appreciated!

Answer Source

Below is the sample code. Value of each variable is mentioned in comment at each step to explain you regarding how it worked:

my_string = "How does one do this How does one do this"

my_list = my_string.split(" ")
# my_list: ['How', 'does', 'one', 'do', 'this', 'How', 'does', 'one', 'do', 'this']

count = 1
my_dict = {}
for item in my_list:
    if item not in my_dict:
        my_dict[item] = count
        count += 1
# my_dict: {'this': 5, 'How': 1, 'does': 2, 'do': 4, 'one': 3}

num_list = [str(my_dict[item]) for item in my_list]
# num_list: ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5']

num_string = ''.join(num_list)
# num_string: '1234512345'

Alternatively, if you need one line solution, you may use list.index() to achieve it. Below is the equivalent code:

num_string = ''.join([str(my_list.index(item)+1) for item in my_list])
# num_string: '1234512345'

where my_list is holding the value from my above example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download