[英]Using a variable as an index for a list
Can't find a way around this anywhere else. 在其他任何地方都找不到解决方法。 Using Python 3.7 使用Python 3.7
rowNum = input
row = [1,2,3,4,5,6,7,8,9]
print(row[rowNum])
This is an overly simplified example of my program. 这是我的程序的过于简化的示例。 Basically all i want to do is make it so that i can use whatever value is entered into "rowNum" as the index. 基本上我要做的就是使它可以使用输入到“ rowNum”中的任何值作为索引。 I'm getting "Keyerror : Number inputted " Not sure how to fix. 我收到“ Keyerror: 输入的数字 ”不确定如何解决。 (I am relativley new to this site so excuse me for bad formatting if any) (我是这个网站的新手,所以请原谅我格式错误)
rowNum = int(input())
row = [1,2,3,4,5,6,7,8,9]
print(row[rowNum])
You have to actually grab the user input: 您实际上必须获取用户输入:
rowNum = int(input("Enter a row number: "))
row = [1,2,3,4,5,6,7,8,9]
print(row[rowNum])
Convert it to an integer, a list will not take a string. 将其转换为整数,列表将不包含字符串。 Here is your output: 这是您的输出:
Enter a row number: 4
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.