在for循环中创建变量

2024-06-16 09:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python3制作一个投票系统,我通过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

如果你知道一个更好的方法来处理这个,请让我知道,因为这似乎没有优化


Tags: 对象方法用户infortkinter过程职位
2条回答

您可以使用^{},它类似于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

^{}可用于确定获胜者:

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

为什么不使用字典:

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'

相关问题 更多 >