Sunday, 15 April 2012

python - Appending list B with indices from enumerated list A -



python - Appending list B with indices from enumerated list A -

i'm new python. when effort re-create list strings , indices, list variable created loop, i'm returned empty list. however, printing list before it's copied returns info want.

this website gave me thought utilize piece b=a[:] (http://henry.precheur.org/python/copy_list). doesn't work when utilize technique b = list(a) same website.

my goal create series of lists 1 list each unique character in user input string. each list begin unique character followed indices of every occurrence of character in 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 i, value in enumerate (xlist): exec "global var%i" %(i) i, value in enumerate(xlist): if value=="%s" %str(xlist[character_count]): value=[value] value.append(i) print value """<--this returns total list""" exec "var%i=value[:]" %(i) exec "print var%i" %(i) """<-- returns empty list""" def enum2(): global character_count global xlength while character_count<xlength: enum() character_count=character_count+1 go on enum2() print var38 """output ['?', 38] output [] desired output ['?', 38] desired output ['?', 38]"""

i'm getting closer want updating dictionary. however, returns 1 index per unique character. want indices.

should utilize set instead of dictionary append indices key/set? possible 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() i, j in enumerate(string_list): string_dict.update({j:i}) print string_dict

an reply has been found!

a solution came after modifying reply (http://stackoverflow.com/a/2285887/3761932) on (python dictionary maps strings set of strings?)

here's have

string=raw_input("input: ") string_lower=string.lower() string_list=list(string_lower) string_dict = dict() j in string_list: string_dict[j]=list() i, j in enumerate(string_list): string_dict[j].append(i) print string_dict

input: shall compare thee 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]}

python list dictionary indexing enumerate

No comments:

Post a Comment