为什么元组列表不可调用?当我调用一个参数为元组列表的函数时,它会显示错误

2024-05-19 12:25:27 发布

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

定义调用上述函数(来宾列表)的函数后。如果元组(不是列表)在同一行中,我如何打印元素

guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")])

我需要以ken is 30 years old and he is a chef的形式输出


Tags: 函数元素列表定义islistchef元组
3条回答

以下代码应按您的要求执行:

for guest in guest_list:
    name = guest[0]
    age = guest[1]
    job = guest[2]
    print(f"{name} is {age} years old and he is a {job}")

如果我理解正确,您需要编写guest_lists()函数来打印每个来宾的信息。在这种情况下,您可以迭代列表并打印每个条目的信息,如-

def guest_list(guests):
    for (name, age, profession) in guests:
        print("{} is {} years old and is a {}".format(name, age, profession))

试试这个:

def guest_list(guests):
    for guest in guests:
        print(f'{guest[0]} is {guest[1]} years old and he is {guest[2]}')

相关问题 更多 >