python的第一步:如何组合两个列表

2024-07-04 08:33:44 发布

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

所以我刚开始学习Python的一些基础知识。因为我是一个非常实际的人,我喜欢用《用Python自动化无聊的东西》一书来做这件事。在

不,这里有一章介绍python中的列表及其优点。 为了实用起见,应该编写一个代码,要求用户输入猫的名字,然后将其添加到列表中。如果不再添加猫名,则应显示所有猫名。在

到现在为止,很公平。所以我想我应该尝试一下,再进一步,通过添加猫的年龄来扩展功能。期望的结果是要求用户输入姓名,然后输入年龄,再次输入姓名,再输入年龄,依此类推。如果用户没有再次输入名字,它应该列出猫的年龄。在

我创建了第二个列表和第二个输入,一切都可以,但我不知道如何将这两个列表或值组合起来。在

它只给我两个名字,然后是两个年龄。在

有人愿意帮我解决这个初学者的问题吗?在

提前谢谢

catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter 
          nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for name in catNames:
            print(" " + name)
        for age in catAges:
            print(" " + age)
        break
    catNames = catNames + [name]
    catAges = catAges + [age]

Tags: ofthe用户name列表age名字姓名
3条回答

一般来说,这类任务将使用dictionaries。在

但如果您要使用列表来解决您的问题,可以这样实现:

catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for i in range(len(catNames)):
            print("Cat number",i, "has the name", catNames[i], "and is", catAges[i], "years old")
        break

    catNames = catNames + [name]
    catAges = catAges + [age]

我想你在找^{}

catNames = ['Fluffy', 'Whiskers', 'Bob']
catAges = [5, 18, 2]
catZip = zip(catNames, catAges)
print(list(catZip))

输出:

^{pr2}$

如果我能正确理解,你想把年龄和名字一起打印吗? 如果是这样的话,你可以这样做:

catNames = []
catAges = []

while True:
    name = input("Enter the name of Cat {} (Or enter nothing to stop): ".format(str(len(catNames) + 1)))
    while name != "":
        age = input("Enter the age of {}: ".format(name)) # Takes inputted name and adds it to the print function.
        catNames.append(name) # Adds the newest name the end of the catNames list.
        catAges.append(age) # Adds the newest age the end of the catNames list.
        break

    if name == "":
        print("\nThe cat names and ages are: ")
        for n in range(len(catNames)):
            print("\nName: {}\nAge: {}".format(catNames[n], catAges[n]))
        break

结果输出:

^{pr2}$

如果你对我所做的有什么意见,请尽管问。在

相关问题 更多 >

    热门问题