当前位置:主页 > 软件编程 > Python代码 >

python返回数组的索引实例

时间:2021-12-16 09:49:56 | 栏目: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

您可能感兴趣的文章:

相关文章