Python: 定义自己的函数 "randomcall"

Python: Define own function called "randomcall"

所以我被困在一个我必须解决的问题上,想知道你们是否可以在我的情况下帮助我(我真的是 python 和编程本身的新手)。所以我得到的任务是,定义一个自己的新函数来从名为“电话簿”的随机人中挑选出字典并打印出来假装打电话给他们。类似于“randomcall(phonebook,10)”之类的东西,然后打印出来:呼叫 Peter at 1800650, and 9 others.

def randomcall(phonebook, number):
    import random
    
    for name in range(phonebook):
        name = random.choice(list(phonebook))
        phonebook = phonebook[name]
        print(f"Let's call {name} with {phonebook}")

phonebook = {"martin": 12345, "anna": 65478, "klaus": 5468764, "hans": 748463, "peter": 84698416, "ulrich": 3416846546, "frank": 4789749, "lukas": 798469, "ferdinand": 68465131}

randomcall(phonebook, 3)

randomcall("", 5)

你可以这样,number将是呼叫人数的范围。

import random

def randomcall(phonebook,number):

    for _ in range(number):
        name = random.choice(list(phonebook.keys()))
        print(f'Lets call {name} with {phonebook[name]}')



phonebook = {"martin":12345,"anna":65478,"klaus":5468764,"hans":748463,"peter":84698416,"ulrich":3416846546,"frank":4789749,"lukas":798469,"ferdinand":68465131}

randomcall(phonebook,3)

输出:

Lets call lukas with 798469
Lets call peter with 84698416
Lets call klaus with 5468764

除了几个小错误外,您的代码是正确的:

  1. 如我上面的所说,不能使用for name in range(phonebook),因为phonebook不是你需要迭代的整数倍。 number 是。此外,迭代中未引用变量 name;它被赋予了新的价值。所以可以换成另一个变量,比如i,在迭代中用的比较多
  2. 要呼叫的人的号码在您的代码中存储在变量 phonebook 下,这是电话簿字典的变量。这使得无法再次访问实际的电话簿。可以在那里使用另一个变量,如 phone

所以完整的代码应该是这样的:

def randomcall(phonebook, number):
    import random

    for name in range(number):
        name = random.choice(list(phonebook))
        phonebook = phonebook[name]
        print(f"Let's call {name} with {phonebook}")


phonebook = {"martin": 12345, "anna": 65478, "klaus": 5468764, "hans": 748463, "peter": 84698416, "ulrich": 3416846546, "frank": 4789749, "lukas": 798469, "ferdinand": 68465131}

randomcall(phonebook, 3)

输出:

Let's call anna with 65478
Let's call klaus with 5468764
Let's call hans with 748463

此外,如 所述,randomcall("", 5) 行用于随机呼叫一个人。实际上,电话簿必须作为 phonebook 参数传递给函数,如果 1 传递给 number 参数,它会生成 1 个随机调用。