2016-12-11 133 views
0

我使用python 3製作投票系統,並根據用戶通過tkinter的輸入獲取每個職位的候選人。爲了這個例子,我不會使用tkinter,因爲它是不必要的。在for循環中創建變量

我有我的候選人在創建時存儲在列表中。由於用戶可以根據自己的需要創建儘可能多的候選人,因此無法知道計數過程需要多少變量。這就是爲什麼我相信我需要使用for循環來創建變量。我怎樣才能做到這一點?

posOne = [] 
f = [x.strip() for x in candidates.split(',')] 
for x in f1: 
    posOne.append(x) 

for z in posOne: 
    #code to create a new variable 

那我就需要一種方法來針對創建的變量,所以當他們收到一票我可以數+1

如果你知道一個更好的方式來處理這個問題,請讓我知道,因爲這似乎並不優化

回答

3

爲什麼不使用詞典:

votes = {candidate.strip(): 0 for candidate in candidates.split(',')} 

這是一本字典的理解,等效於:

votes = {} 
for candidate in candidates.split(','): 
    votes[candidate.strip()] = 0 

的,當你得到一個候選人投票:

votes[candidate] += 1 

決出勝負:

winner = max(votes, key=votes.get) 

如:

>>> candidates = 'me, you' 
>>> votes = {candidate.strip(): 0 for candidate in candidates.split(',')} 
>>> votes 
{'me': 0, 'you':0} 
>>> votes[you] += 1 
>>> winner = max(votes, key=votes.get) 
>>> winner 
'you' 
+0

我從來沒有使用類型的字典或地圖嗎,我將如何確定贏家使用這個? – Shniper

+0

如果你不介意,你可以分解代碼的每一部分,因爲我沒有使用過之前的字典或地圖,這將大大幫助我理解如何編輯我的實際程序的答案 – Shniper

1

你可以使用collections.Counter這是dict其中值爲計數的對象:

>>> from collections import Counter 
>>> candidates = 'Jack, Joe, Ben' 
>>> votes = Counter({x.strip(): 0 for x in candidates.split(',')}) 

投票會做這樣的:

>>> votes['Jack'] += 1 
>>> votes['Jack'] += 1 
>>> votes['Ben'] += 1 

而且most_common可以用來確定贏家:

>>> votes.most_common(1) 
[('Jack', 2)]