I'm new to python. When I attempt to copy list strings and their indices, to a list variable created by a loop, I'm returned an empty list. However, printing the list before it's copied returns all the data I want.
This website gave me the idea to use a slice b=a[:] (http://henry.precheur.org/python/copy_list). It also doesn't work when I use this technique b = list(a) from the same website.
My goal is to create a series of lists with only one list for each unique character in a user input string. Each list would begin with the unique character followed by the indices of every occurrence of that character in the original user string.
for i, value in enumerate (xlist):
exec "var%i=list()" %(i)
exec "global var%i" %(i)
def enum():
global character_count
global xlist
for i, value in enumerate (xlist):
exec "global var%i" %(i)
for i, value in enumerate(xlist):
if value=="%s" %str(xlist[character_count]):
value=[value]
value.append(i)
print value
"""<--This returns a full list"""
exec "var%i=value[:]" %(i)
exec "print var%i" %(i)
"""<-- This returns an empty list"""
def enum2():
global character_count
global xlength
while character_count<xlength:
enum()
character_count=character_count+1
continue
enum2()
print var38
"""output ['?', 38]
output []
desired output ['?', 38]
desired output ['?', 38]"""
I'm getting closer to what I want by updating a dictionary. However, this returns only one index per unique character. I want all the indices.
Should use a set instead of a dictionary to append indices to a key/set? Is this possible with a dictionary?
"""Output
Input: Hello
{'h': 0, 'e': 1, 'l': 3, 'o': 4}
Desired
{'h': 0, 'e': 1, 'l': [2, 3], 'o': 4}"""
string=raw_input("Input: ")
string_lower=string.lower()
string_list=list(string_lower)
string_dict = dict()
for i, j in enumerate(string_list):
string_dict.update({j:i})
print string_dict
An answer has been found!
A solution came after modifying an answer (https://stackoverflow.com/a/2285887/3761932) on (Python dictionary that maps strings to a set of strings?)
Here's what I have
string=raw_input("Input: ")
string_lower=string.lower()
string_list=list(string_lower)
string_dict = dict()
for j in string_list:
string_dict[j]=list()
for i, j in enumerate(string_list):
string_dict[j].append(i)
print string_dict
Input: Shall I compare thee to a summer's day?
{'a': [2, 12, 24, 36], ' ': [5, 7, 15, 20, 23, 25, 34], 'c': [8], 'e': [14, 18, 19, 30], 'd': [35], "'": [32], 'i': [6], 'h': [1, 17], 'm': [10, 28, 29], 'l': [3, 4], 'o': [9, 22], 'p': [11], 's': [0, 26, 33], 'r': [13, 31], 'u': [27], 't': [16, 21], 'y': [37], '?': [38]}