简体   繁体   English

Python-返回列表枚举的整数值

[英]Python - Return integer value for list enumeration

Is there a cleaner way to get an integer value of the position of a list item in this code: 有没有更干净的方法来获取此代码中列表项位置的整数值:

a = ['m', 'rt', 'paaq', 'panc']
loc = [i for i, x in enumerate(a) if x == 'rt']
loc_str = str(loc).strip('[]')
loc_int = int(loc_str)
id_list = a[loc_int + 1:]
print id_list

Returns all items after 'rt' as a list ['paaq', 'panc'] 以列表的形式返回“ rt”之后的所有项目['paaq','panc']

Yes, use list.index() . 是的,使用list.index()

a = ['m', 'rt', 'paaq', 'panc']
id_list = a[a.index('rt')+1:]
assert id_list == ['paaq', 'panc']

Or, to minimally change your program: 或者,以最小的方式更改程序:

a = ['m', 'rt', 'paaq', 'panc']
loc_int = a.index('rt')
id_list = a[loc_int + 1:]
print id_list

References: 参考文献:

a[a.index('rt') + 1:]

What this is doing is slicing the array, starting at where a.index('rt') . 这是在数组,从a.index('rt') not specifying an end :] means we want until the end of the list. 不指定结尾:]表示我们想要直到列表结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM