Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用百分号的Python字典操作_Python_List_Dictionary_Percentage - Fatal编程技术网

使用百分号的Python字典操作

使用百分号的Python字典操作,python,list,dictionary,percentage,Python,List,Dictionary,Percentage,我有一个包含两本词典的列表: >>> x [{'sby_0': 'sb0'}, {'sby_1': 'sb1'}] 我想使用百分号获取第二个命令项: i = 1 x[1]["sby_%s" %i] 但它不起作用。我该怎么办?您的代码没有问题: In [6]: x = [{'sby_0': 'sb0'}, {'sby_1': 'sb1'}] In [7]: i = 1 In [8]: x[1]['sby_%s' % i] Out[8]: 'sb1' 编辑您在评论中发布的

我有一个包含两本词典的列表:

>>> x
[{'sby_0': 'sb0'}, {'sby_1': 'sb1'}]
我想使用百分号获取第二个命令项:

i = 1
x[1]["sby_%s" %i]

但它不起作用。我该怎么办?

您的代码没有问题:

In [6]: x = [{'sby_0': 'sb0'}, {'sby_1': 'sb1'}]

In [7]: i = 1

In [8]: x[1]['sby_%s' % i]
Out[8]: 'sb1'

编辑您在评论中发布的错误消息是
x[1][“sby_u%i”,i]
。问题在于逗号;应将其替换为百分号。

您的代码工作正常:

>>> x = [{'sby_0': 'sb0'}, {'sby_1': 'sb1'}]
>>> i = 1
>>> x[1]["sby_%s" %i]
'sb1'
但是,我会使用
%d
而不是
%s
,因为
I
是一个数字

您没有发布的代码中的错误是,您使用了
“sby_u%s”,i
而不是
“sby_%s”%i
<代码>%执行字符串格式设置(您需要的格式),而
创建元组(本例中您不需要的格式)


它按预期工作。也许可以进一步讨论您的问题,并发布更多关于您的用法的信息。

我得到了以下信息:
>>x[1][“sby_%s”,I]回溯(最近一次调用):文件“”,第1行,在x[1][“sby_%I”,I]keyrerror:('sby_%I',1)
您编写了
而不是
%
,并且您的dict没有键
('sby_%I',1)
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = [{'sby_0': 'sb0'}, {'sby_1': 'sb1'}]
>>> i = 1
>>> x[1]
{'sby_1': 'sb1'}
>>> x[1]['sby_%s' % i]
'sb1'