0

我想知道列表中是否存在索引,并访问它的值,但我不知道该怎么做。我需要的是这样的:

my_list = ["a", "b", "c"]
if(my_list[3] == "d"):
 print("Something")
elif(my_list[3] != "d"): 
 print("Something again")

如果有第三个索引我想做点什么,如果没有,什么也不做。

请注意,我需要检查“d”是否在索引 3 中,如果索引 3 中没有“d”,则它属于 elif 块中的其他内容,但是,如果没有索引 3,则什么也不做

4

4 回答 4

1

由于您想知道第三个索引是否存在:

my_list = ["a", "b", "c"]
if(3 in range(0,len(my_list))):
  if my_list[3] == 'd':
    print("Something")
  elif(my_list[3] != "d"): 
    print("Something again")
于 2021-07-27T09:10:23.227 回答
0

如果您运行代码,您将收到“IndexError: list index out of range”。如果您指的是列表中的第三个元素,那就是 my_list[2] 这可以使用 'in' 或 'not in' 向后写。

my_list = ["a", "b", "c"]

if "d" in my_list[2]:
    print("Something")
else:
    pass
于 2021-07-27T09:04:01.703 回答
0

你可以只使用try - except

try 块允许您测试代码块的错误。

except 块允许您处理错误。

my_list = ["a", "b", "c"]
try:
    # if index exist it will execute this part of code
    if(my_list[3] == "d"):
        print("Something")
    elif(my_list[3] != "d"): 
        print("Something again")
except IndexError:
    print ("index doesnt exist")
于 2021-07-27T09:09:01.267 回答
0

您可以使用此代码段返回TrueFalse

def index_in_list(a_list, index):
    print(index < len(a_list))


a_list = ["a", "b", "c", "d"]
if len(a_list) == 4:
    index_in_list(a_list, "d") # output: True
于 2021-07-27T09:09:13.940 回答