所以我刚开始学习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]
答案 0 :(得分:1)
我认为您正在寻找zip
:
catNames = ['Fluffy', 'Whiskers', 'Bob']
catAges = [5, 18, 2]
catZip = zip(catNames, catAges)
print(list(catZip))
输出:
[('Fluffy', 5), ('Whiskers', 18), ('Bob', 2)]
答案 1 :(得分:0)
一般情况下,您会使用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]
答案 2 :(得分:0)
如果我能正确理解你想要一起打印年龄和名字吗? 好吧,如果那样你可以这样做:
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
结果输出:
Enter the name of Cat 1 (Or enter nothing to stop): Cat1
Enter the age of Cat1: 5
Enter the name of Cat 2 (Or enter nothing to stop): Cat2
Enter the age of Cat2: 7
Enter the name of Cat 3 (Or enter nothing to stop): # I hit enter here so it skips.
The cat names and ages are:
Name: Cat1
Age: 5
Name: Cat2
Age: 7
如果您对我所做的事有任何疑问,请随便询问。