1. 程式人生 > >python返回陣列的索引

python返回陣列的索引

使用python裡的index
nums = [1, 2, 3, 4, 5, 6, 1, 9]
print nums.index(max(nums))
print nums.index(1)

該方法同樣適合於字串:

str1 = 'abcd'
print str1.index('c')

但是對於陣列或者字串裡面含有不止一個要檢索的數字時,只會返回第一個元素的索引。

nums = [1, 2, 3, 4, 5, 6, 1, 9]
print nums.index(2)
print nums[::-1].index(2)

用這種方法可以判斷某個元素在陣列或字串中是否只出現一次。

正序index + 逆序index = 陣列或者字串的長度-1