我有一个python列表,如下所示:
['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
目前,我通过:分割每个元素来创建列表列表如:
[['NEW','kim','OPERATOR'], ['DELETE','joe','USER_ROLE_GUEST']]
然后像list[i][j]
一样访问它。
是否有任何好的pythonic方法可以避免所有这些并直接访问我需要的元素?
答案 0 :(得分:2)
如果您的目的(不清楚)是不创建新列表(如果原始列表很大,这可能会很昂贵),并且数据结构始终相同,您可以快速拆分内部字符串:
a = ['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
a[0].split(":")[0] # returns NEW
顺便说一下,在一个元组列表(或更好的,命名元组)中转换列表将是编程POV的更好方法。
答案 1 :(得分:0)
您可以使用生成器表达式并根据需要弹出元素:
l = ['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
spl = (sub.split(":") for sub in l)
a = next(spl)
print(a[0])
b = next(spl)
print(b[0])
或者只是一个生成器表达式并迭代:
spl = (sub.split(":") for sub in l)
for ele in spl:
print(ele)
['NEW', 'kim', 'OPERATOR']
['DELETE', 'joe', 'USER_ROLE_GUEST']
答案 2 :(得分:0)
您可以使用以下功能:
>>> def find_element(i,j,li):
... try:
... return li[i].split(':')[j]
... except IndexError:
... print 'your index is out of range'
...
>>> l =['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
>>> find_element(1,4,l)
your index is out of range
>>> find_element(1,2,l)
'USER_ROLE_GUEST'