我正在尝试编写一个函数,该函数返回一个列表,其中包含名称在文件中出现的次数。我有两个帮助程序功能,它们遍历文件并获得两个列表,一个带有所有名称,然后另一个带有所有唯一名称。我想使用唯一名称并将它们与所有名称进行比较,并计算唯一名称出现在所有名称列表中的次数。
#call getAllPeople helper function to get list
allName=getAllPeople(fileName)
#call getUniquePeople from helper function to get comparison
uniNam=getUniquePeople(fileName)
#give empty list
namNum=[]
#initiate counter
count=0
#iterate through list
for name in allName:
#if name is in getUniquePeople(fileName)
if name in uniNam:
#add to count
count = count+1
return count
我正在寻找:
['bob:4', 'jane:4', 'pam:2', 'batman:1']
在和它一起玩时:
#give empty list
namCount=[]
#initiate counter
count=0
#iterate through list
for name in range(len(allName)):
#if name is in getUniquePeople(fileName)
if name in uniNam:
#add to count
count = count+1
#append namCount with
namCount.append(name +':'+str(count))
return namCount
我一无所获
答案 0 :(得分:1)
正如@Hoog所说,字典更适合解决这个问题。
# make a new empty dictionary
results = {}
for name in allName:
if name in uniNam:
# if name is already in the results dictionary, add 1 to its count
if name in results:
results[name] = results[name] + 1
# otherwise create a new name in the dictionary with a count of 1
else:
results[name] = 1
{'bob': 4, 'jane': 4, 'pam': 2}
编辑-如果您绝对必须只使用列表:
# make new lists for holding names and counts
names = []
name_counts = []
for name in allName:
if name in uniNam:
# if name is already in our list, add 1 to the the corresponding entry in the name_counts list
if name in names:
position = names.index(name)
name_counts[position] = name_counts[position] + 1
# otherwise add this name to our lists with a count of 1
else:
names.append(name)
name_counts.append(1)
# now combine our two lists into the final result
final_list = []
for position in range(len(names)):
final_list.append(names[position] + ':' + str(name_counts[position]))
答案 1 :(得分:0)
您可以使用Counter实现此目的。
from collections import Counter
names = ['John G.', 'Mark T.', 'Brian M.', 'Mark T.', 'Kit H.'] # All names
c = Counter(names)
print(c)
Output:
Counter({'Mark T.': 2, 'John G.': 1, 'Brian M.': 1, 'Kit H.': 1})