Python列表/索引查询

Iri*_*Gal 0 python list

我要求用户输入一个数字,我要在其中打印列表中该索引点处的项目.

这是我目前的代码:

List = ["a", "b", "c", "d", "e", "f"]

print "The list has the following", len(List), "list:", List

new_item = raw_input("Which item would you like to add? ")
List.append(new_item)
print "The list has the following", len(List), "items:", List

Number = raw_input ("Please select a number: ")
Run Code Online (Sandbox Code Playgroud)

Mar*_*air 5

首先尝试转换Number为整数:

i = int(Number)                                                                 
print "You selected:", List[i]
Run Code Online (Sandbox Code Playgroud)

顺便说一句,将变量设置为小写是一种很好的Python风格,并保留以类的大写字母开头的标识符.所以,而不是List你可以使用my_list而不是Number只使用number.(您不应该将其list用作变量名,因为这会隐藏内置list类型.)