📜  Python - 列表中元素的负索引

📅  最后修改于: 2022-05-13 01:55:24.864000             🧑  作者: Mango

Python - 列表中元素的负索引

给定一个元素列表,在列表中找到它的负索引。

方法 #1:使用index() + len()

在这里,我们使用 index() 获取元素的索引,然后从列表长度中减去它以获得所需的结果。

Python3
# Python3 code to demonstrate working of
# Negative index of Element
# Using index() + len()
 
# initializing list
test_list = [5, 7, 8, 2, 3, 5, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Element
K = 3
 
# getting length using len() and subtracting index from it
res = len(test_list) - test_list.index(K)
 
# printing result
print("The required Negative index : -" + str(res))


Python3
# Python3 code to demonstrate working of
# Negative index of Element
# Using ~ operator + list slicing + index()
 
# initializing list
test_list = [5, 7, 8, 2, 3, 5, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Element
K = 3
 
# -1 operator to reverse list, index() used to get index
res = ~test_list[::-1].index(K)
 
# printing result
print("The required Negative index : " + str(res))



输出:

The original list is : [5, 7, 8, 2, 3, 5, 1]
The required Negative index : -3

方法 #2:使用 ~运算符+列表切片+ index()

在此,我们使用切片反转列表,并使用 ~运算符获取否定,使用 index() 获取所需的负索引。

蟒蛇3

# Python3 code to demonstrate working of
# Negative index of Element
# Using ~ operator + list slicing + index()
 
# initializing list
test_list = [5, 7, 8, 2, 3, 5, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Element
K = 3
 
# -1 operator to reverse list, index() used to get index
res = ~test_list[::-1].index(K)
 
# printing result
print("The required Negative index : " + str(res))

 
输出:

The original list is : [5, 7, 8, 2, 3, 5, 1]
The required Negative index : -3