使用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