問題描述
danh sách trong python, vòng lặp for, mảng (list in python, loop for, array)
as a green hand python programmer, I have a little problem, I'll appreciate if somebody can help!!
I have two lists
a list of random repeated numbers(unknow size) like:
number = [44,198,57,48,658,24,7,44,44,44..]
for n in number I want to give these numbers to a list of people in order, one number for one person. If a number repeat, the program will find out the person whom got this number when the first time it shows up. It means I want to print a list like
people = [1,2,3,4,5,6,7,1,1,1...]
print people
參考解法
方法 1:
Store the mapping from numbers to indexes in a dict
, and update it as you go.
numbers = [44,198,57,48,658,24,7,44,44,44.]
index_mapping = {}
indexes = []
next_index = 1
for number in numbers:
if number in index_mapping:
# already seen
indexes.append(index_mapping[number])
else:
# a new one
indexes.append(next_index)
index_mapping[number] = next_index
next_index += 1
print indexes