簡體   English   中英

計算字符串在列表中出現的次數

[英]Count the number of times a string appears in a list

我正在嘗試編寫一個函數,該函數返回一個列表,其中包含名稱在文件中出現的次數。 我有兩個幫助函數,它們遍歷文件並獲得兩個列表,一個包含所有名稱,另一個包含所有唯一名稱。 我想使用唯一名稱並將它們與所有名稱進行比較,並計算名稱唯一名稱出現在所有名稱列表中的次數。

    #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 

我一無所獲

正如@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]))

您可以使用 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})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM