在for循环中创建变量

时间:2016-12-11 02:25:44

标签: python variables for-loop

我正在使用python 3进行投票系统,我根据用户通过tkinter输入获得每个职位的候选人。为了这个例子,我不会使用tkinter,因为它是不必要的。

我的候选人在创建时存储在列表中。由于用户可以根据需要创建尽可能多的候选者,因此无法知道计数过程需要多少变量。这就是为什么我认为我需要使用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

如果你知道更好的方法来处理这个问题,请告诉我,因为这似乎没有得到优化

2 个答案:

答案 0 :(得分: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)

e.g:

>>> 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'

答案 1 :(得分: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)]