Python-变量作为列表索引
我想知道这在python中是否可行。 我以这种方式访问列表:Python-变量作为列表索引,python,list,indexing,Python,List,Indexing,我想知道这在python中是否可行。 我以这种方式访问列表: print list[0]['name'] 这很好。有没有办法使用变量? 我的意思是: 谢谢你的建议 一些细节: 我遇到过这样的情况: a = [{"name":"someone", "age":23}] print a[0]['name'] 但由于我需要将“[0]['name']”作为参数传递,我想了解这是否可行。 谢谢 cips通常是这样的,但您基本上需要转换字符串以执行索引 因此,首先,您可以使用repr >>&
print list[0]['name']
这很好。有没有办法使用变量?
我的意思是:
谢谢你的建议
一些细节:
我遇到过这样的情况:
a = [{"name":"someone", "age":23}]
print a[0]['name']
但由于我需要将“[0]['name']”作为参数传递,我想了解这是否可行。
谢谢
cips通常是这样的,但您基本上需要转换字符串以执行索引
因此,首先,您可以使用repr
>>> l = [{'name': 'bob'}]
>>> repr(l)
"[{'name': 'bob'}]"
然后,如果将其与索引操作连接起来
>>> a = "[0]['name']"
>>> repr(l) + a
"[{'name': 'bob'}][0]['name']"
然后eval
整个事情,它应该会起作用
>>> eval(repr(l) + a)
'bob'
您可以使用函数eval('a[0][name]”),它将以python代码的形式计算其中的字符串 以下是参考资料:
您可以使用exec命令
exec("print(list{})".format(a))
我希望它能工作这是一个简单的问题,即从字符串
“[0]['name']”
中提取索引/键,然后使用这些键对列表/目录结构进行索引
data = [{"name":"someone", "age":23}]
keys = "[0]['name']"
# split the string into a list of indices/keys
keys = keys[1:-1].split('][')
# keys = ['0', "'name'"]
# the keys are all strings, so we have to convert
# each individual key to the correct type
import ast
keys = [ast.literal_eval(key) for key in keys]
# keys = [0, 'name']
# now use the list of indices/keys we generated to get the value
value = data
for key in keys:
value = value[key]
print(value) # output: someone
我希望不要脱离上下文,但如果可以的话,也许可以使用这样的函数 将
s=“[0]['name']”转换为s=(0,'name')
:
如果要将“[0]['name']”
转换为(0,'name')
,可以尝试以下操作:
import re
reg = re.findall(r'\[(\d*?)\]|\[\'(\w*?)\'\]', "[0]['name']")
s = [int(index[0]) if not index[1] else index[1] for index in reg]
# [0, 'name']
它会将索引转换为正确的类型,以便使用列表或dict。您需要解释为什么需要使用它。否则,它只能通过eval
或exec
来完成。是否要使用此特定字符串为列表编制索引,或者变量是否具有其他值?例如a=[0,'name']
?请参阅下面我的编辑。欢迎使用StackOverflow。请阅读以在将来写出更好的答案。请不要提倡使用eval
或exec
。不使用eval
解决OP的问题几乎是微不足道的eval
无缘无故地在代码中打开了一个巨大的安全漏洞。请不要提倡使用eval
或exec
。不使用exec
解决OP的问题几乎是微不足道的exec
无缘无故地在代码中打开了一个巨大的安全漏洞。请不要这样做。在这种情况下,避免eval
几乎是微不足道的;您可以轻松地将字符串“[0]['name']”
解析为类似[0,'name']
的列表,然后使用这些值对a
进行索引。
def search_index(obj, itero):
try:
return search_index(obj[next(itero)], itero)
except StopIteration:
return obj
a = [{"name":"someone", "age":23}]
s = (0, 'name')
result = search_index(a, iter(s))
# >>> result = 'someone'
import re
reg = re.findall(r'\[(\d*?)\]|\[\'(\w*?)\'\]', "[0]['name']")
s = [int(index[0]) if not index[1] else index[1] for index in reg]
# [0, 'name']