gpt4 book ai didi

python - 验证字符串输入并将其连接到列表

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:11 24 4
gpt4 key购买 nike

studentNumber = len(age) - 1
age[studentNumber] = 0
house[studentNumber] = ''
reactionTime[studentNumber] = 0

while True:
try:
age[studentNumber] = int(input("What is the age of the student: "))
except ValueError:
age[studentNumber] = int(input("What is the age of the student: "))

if age[studentNumber] in range(12, 17):
break

house[studentNumber] = input("Which house is the student in (Saturn/Mars): ").lower()
while house[studentNumber] not in {"saturn", "mars"}:
house[studentNumber] = input("Which house is the student in (Saturn/Mars): ").lower()

age.append(0)
house.append('')
reactionTime.append(0)

print(age + " " + house + " " + reactionTime)

我正在尝试将输入验证为“saturn”或“mars”的字符串,但我收到错误 TypeError: can only concatenate list (not "str") to list 当我尝试将它添加到我的列表时

命令行:

What would you like to do:
1. Enter new information
2. House-based statsitics
3. Specific Criteria statistics
Enter 1 2 or 3: 1
What is the age of the student: 12
Which house is the student in (Saturn/Mars): saturn
Traceback (most recent call last):
File "python", line 46, in <module>
File "python", line 32, in newInfo
TypeError: can only concatenate list (not "str") to list

最佳答案

agehousereactionTime 是列表,不能与字符串连接。

您应该压缩这三个列表并遍历输出的项目。

改变:

print(age + " " + house + " " + reactionTime)

到:

for a, h, r in zip(age, house, reactionTime):
print(a, h, r)

关于python - 验证字符串输入并将其连接到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52602835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com