【问题标题】:How to use an integer variable as a parameter for a function?如何使用整数变量作为函数的参数?
【发布时间】:2018-10-28 07:11:51
【问题描述】:

我正在尝试编写一段代码来计算三个不同候选人的选票,并且我正在使用一个函数,该函数使用变量名称(A、B 或 C)作为参数。

我正在尝试使用它,以便每当为该候选人计票时,它都会调用该函数以将该候选人的变量增加 1。但是,我尝试过的所有方式都将始终是所有 3 位候选人计为 0 票,除非我完全删除该功能。

我尝试了几种不同的方法来使变量成为全局变量,但它们都给出了相同的结果。

A = 0
B = 0
C = 0

def after_vote(letter):
    letter = letter + 1
    print("Thank you for your vote.")

def winner(winner_letter, winner_votes):
    print("The winner was", winner_letter, "with", str(winner_votes), "votes.")

while True:
    vote = input("Please vote for either Candidate A, B or C. ").upper()
    if vote == "A":
        after_vote(A)
    elif vote == "B":
        after_vote(B)
    elif vote == "C":
        after_vote(C)
    elif vote == "END":
        print("Cadidate A got", str(A), "votes, Candidate B got", str(B), "votes, and Candidate C got", str(C), "votes.")
        if A > B and A > C:
            winner("A", A)
            break
        elif B > A and B > C:
            winner("B", B)
            break
        elif C > A and C > B:
            winner("C", C)
            break
        else:
            print("There was no clear winner.")
            break
    else:
        print("Please input a valid option.")

【问题讨论】:

  • 你不能在 Python 中传递变量。见nedbatchelder.com/text/names.html
  • 整数是不可变对象,在函数内部更改它们不会影响调用者。更好的方法是使用字典,将这些字母作为键,将投票计数作为值,然后在每次投票后不断更新每个键的相应计数。

标签: python python-3.x function global-variables parameter-passing


【解决方案1】:

您需要将可变数据类型传递给函数,以便您可以修改它。尝试将您的候选人包装到列表或字典中。

candidates = {'A':0, 'B':0, 'C':0}

def after_vote(letter):
    global candidates
    if letter in candidates:
        candidates[letter] += 1
        print("Thank you for your vote.")
    else:
        print("No such candidate: Your vote is invalid.")

【讨论】:

  • 在函数顶部调用global candidates是没用的。没有它也能达到同样的效果。
【解决方案2】:

首先,这个想法是错误的。您不想处理全局变量并传递名称。可以这样做,但这是个坏主意。

更好的选择是将要修改的变量传递给函数。然而,整数的技巧是它们是不可变的,所以你不能传递一个整数来被函数修改,就像你在 C 中那样。

剩下的是:

  • 向函数传递一个值,从函数返回修改后的值;或
  • 将持有值的可变对象传递给函数

这就是理论,这里是如何做到的......

方案一:传一个值,返回修改后的值

def after_vote(value):
    print("Thank you for your vote.")
    # Instead of modifying value (impossible), return a different value
    return value + 1

A = after_vote(A)

解决方案 2:传递一个“可变整数”

class MutableInteger:
    def __init__(value):
        self.value = value

A = MutableInteger(0)

def after_vote(count):
    # Integers cant be modified, but a _different_ integer can be put
    # into the "value" attribute of the mutable count object
    count.value += 1
    print("Thank you for your vote.")

after_vote(A)

解决方案 3:传递所有投票的(可变!)字典

votes = {'A': 0, 'B': 0, 'C': 0}

def after_vote(votes, choice):
    # Dictionaries are mutable, so you can update their values
    votes[choice] += 1
    print("Thank you for your vote.")

after_vote(votes, "A")

解决方案 4(最糟糕的!):实际执行您的要求

def after_vote(letter):
    # Global variables are kept in a dictionary. globals() returns that dict
    # WARNING: I've never seen code which does this for a *good* reason
    globals()[letter] += 1
    print("Thank you for your vote.")

【讨论】:

    【解决方案3】:

    在您的情况下,最好定义 3 个函数,每个候选者一个:

    A = 0
    B = 0
    C = 0
    
    def after_vote_A():
        global A
        A += 1
        print("Thank you for your vote.")
    
    def after_vote_B():
        global B
        B += 1
        print("Thank you for your vote.")
    
    def after_vote_C():
        global C
        C += 1
        print("Thank you for your vote.")
    

    别忘了使用关键字global,否则你定义一个局部变量。

    另一种方法是将投票存储在dict

    votes = {'A': 0, 'B': 0, 'C': 0}
    
    def after_vote(letter):
        votes[letter] += 1
        print("Thank you for your vote.")
    

    演示:

    after_vote('A')
    after_vote('B')
    after_vote('A')
    after_vote('A')
    print(votes)
    

    你得到:

    Thank you for your vote.
    Thank you for your vote.
    Thank you for your vote.
    Thank you for your vote.
    {'A': 3, 'B': 1, 'C': 0}
    

    【讨论】:

    • 增加每个值的函数不可能是最优的。
    【解决方案4】:

    如果没有两个候选人使用相同的名字,最简单的方法是使用字典。

    candidates = {"A":0, "B":0, "C":0}
    

    从那里,您可以设置一个函数来在字典中查找一个值并递增它:

    def update_vote(candidate):
        candidates[candidate] += 1
    

    或者哎呀,您可以就地更新投票,而不是调用函数:

    candidates[candidate] += 1
    

    一个更 Pythonic 的方法是让每个候选人成为一个可以更新自己的投票计数的对象。

    class Candidate(object):
        def __init__(self):
            # This is the "constructor" for the object.
            # It is run whenever an instance of this object is created.
            # We want it to "spawn in" with zero votes.
            self.vote_count = 0
        def update_vote(self):
            self.vote_count += 1
    

    这似乎更接近您在最初的帖子中得到的内容。您将按如下方式创建一个对象:

    A = Candidate()
    B = Candidate()
    C = Candidate()
    

    然后,在您的主循环中,您只需告诉每个对象进行自我更新:

    if vote == "A":
        A.update_vote()
    

    最后,当你统计选票时,你只需要让每个对象给你他们的“投票”计数:

    if A.vote_count > B.vote_count and A.vote_count > C.vote_count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2011-02-14
      • 1970-01-01
      相关资源
      最近更新 更多