带 zip 的 for 循环 python

for loop with zip in python

我想使用 zip 迭代现有列表。

我用下面的代码做到了。当前输出只是 Name --> Name.

如何使用新创建的列表,或者如果不能使用其他列表来打印以下句子:

“#NAME 是#AGE 岁,他们可以在#NUMBER 被调用”。是否可以在一个循环中完成此操作?

    birth_years = {"Alice": "1990", "Bob": "1990", "Carol": "1995", "Felix":"1995","Max":"1995","Chris":"1998","Lea":"1998","Linn":"1998","Julia":"1998"}
    book = {"Alice": "+1554", "Bob": "+1885", "Carol": "+1006", "Felix":"+1604", "Max":"+1369","Chris":"+1882","Lea":"+1518","Linn":"+1742","Julia":"+1707"} 


   def test(birth_years, books):
      new_list = []
      for birth_year, book in zip(birth_years, books):
        new_list.append(f'{birth_year} -> {book}')
      return new_list

   print(test(birth_years,books))

谢谢!!

BR

zip 不是这里的问题。问题是您的 for 循环将简单地遍历字典中的键,而不是键和值(参见 this answer

正确的做法是:

birth_years = {"Alice": "1990", "Bob": "1990", "Carol": "1995", "Felix":"1995","Max":"1995","Chris":"1998","Lea":"1998","Linn":"1998","Julia":"1998"}
books = {"Alice": "+1554", "Bob": "+1885", "Carol": "+1006", "Felix":"+1604", "Max":"+1369","Chris":"+1882","Lea":"+1518","Linn":"+1742","Julia":"+1707"} 


def test(birth_years, books):
    new_list = []
    for [name, birth_year], [unused, number] in zip(birth_years.items(), books.items()):
        new_list.append(f'{name} is {2022 - int(birth_year)} years old, and they can be called at {number}')
    return new_list

print(test(birth_years,books))