提问人:Zak Smith 提问时间:1/26/2023 最后编辑:Zak Smith 更新时间:1/26/2023 访问量:40
如何在 Python 中链接两个列表中的项目 [duplicate]
How to link items in two lists in Python [duplicate]
问:
我刚开始在大学学习 Python,对如何正确链接两个列表有点困惑。
我需要编写一个程序,该程序使用输入的用户名和年龄,并将其与姓名和年龄列表进行比较,并打印一行,例如“Eric 是 X 岁并且比(输入所有年轻者的名字”+对于年轻的人也是如此。
我不确定如何将每个名字链接到一个年龄,然后用它来只打印出年长/年轻的人的名字。
正确的打印输出如下所示:
以西结今年 25 岁,比鲍勃和扎克年轻。
以西结今年 25 岁,比约翰、埃里克、蒂姆、乔治还大。
我们不允许使用字典。 谢谢。
name = input("What is your name of your character? ")
age = int(input("How old is your character? "))
names = ["John",
"Eric",
"Bob",
"Tim",
"George",
"Zac",]
ages = [59, 39, 12, 80, 26, 20,]
for items in ages:
if age > items:
print(f'{name} is {age} years old, and they are younger than {items}')
答:
0赞
FedeG
1/26/2023
#1
如果不能使用词典,则可以使用列表的索引。
溶液:
for index, age in enumerate(ages):
olders = [names[i] for i, other_age in enumerate(ages) if other_age > age]
print(f"{names[index]} is {age} years old, and they are younger than {', '.join(olders)}")
评论
0赞
FedeG
1/26/2023
另一种解决方案是使用 zip,但此函数返回一个带有元组的可迭代对象(将两个列表合并到一个元组列表中,其中包含通过索引连接的元素)
上一个:从用户处获取数字列表作为输入
评论
for item_name, item_age in zip(names, ages):