Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.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

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-在dict上循环。在dict中搜索元素_Python_List_Dictionary - Fatal编程技术网

Python-在dict上循环。在dict中搜索元素

Python-在dict上循环。在dict中搜索元素,python,list,dictionary,Python,List,Dictionary,结果: IDAX = [3, 8, 10, 12] AXID = [3, 5, 6, 8, 10, 12] BT = [1, 1, 1, 1, 0, 0] BT = [str(x) for x in BT] AX_BR = dict(zip(AXID, BT)) 现在,我希望IDAX中的每个元素都有正确的BT值 如何在听写器中搜索元素 谢谢 不需要在dict上循环;您需要的是非常基本的dict用法: {3: '1', 5: '1', 6: '1', 8: '1', 10: '0', 12:

结果:

IDAX = [3, 8, 10, 12]
AXID = [3, 5, 6, 8, 10, 12]
BT = [1, 1, 1, 1, 0, 0]

BT = [str(x) for x in BT]

AX_BR = dict(zip(AXID, BT))
现在,我希望IDAX中的每个元素都有正确的BT值

如何在听写器中搜索元素


谢谢

不需要在dict上循环;您需要的是非常基本的dict用法:

{3: '1', 5: '1', 6: '1', 8: '1', 10: '0', 12: '0'}
或者,如果您的意思是想要一个配对列表(IDAX、BT):


您使用的列表变量名称与迭代变量名称相同

[(idax, BT[idax]) for idax in IDAX]

我想我用一个循环解决了这个问题

>>> IDAX = [3, 8, 10, 12]
>>> AXID = [3, 5, 6, 8, 10, 12]
>>> BT = [1, 1, 1, 1, 0, 0]
>>> BT = [str(x) for x in BT]
>>> AX_BR = dict(zip(AXID, BT))
>>> print AX_BR
{3: '1', 5: '1', 6: '1', 8: '1', 10: '0', 12: '0'}
>>> {i: AX_BR[i] for i in IDAX}
{3: '1', 8: '1', 10: '0', 12: '0'}

也许不是最好的解决方案,但它很有效。

谢谢。我的目标是一个成对的列表(IDAX,BT),但这个错误即将到来:列表索引必须是整数,而不是列表。显然,你做了一些与我的示例不同的事情:你不应该通过整个IDAX列表而仅仅通过它的元素来索引BT。在我的列表理解中,这是通过使用循环变量作为索引来实现的,它在任何给定时间都是IDAX元素之一。如果这一切对您来说没有多大意义,请发布一个完整的演示问题的最小示例。
{key:int(AX_BR[key])for key in IDAX}
>>> IDAX = [3, 8, 10, 12]
>>> AXID = [3, 5, 6, 8, 10, 12]
>>> BT = [1, 1, 1, 1, 0, 0]
>>> BT = [str(x) for x in BT]
>>> AX_BR = dict(zip(AXID, BT))
>>> print AX_BR
{3: '1', 5: '1', 6: '1', 8: '1', 10: '0', 12: '0'}
>>> {i: AX_BR[i] for i in IDAX}
{3: '1', 8: '1', 10: '0', 12: '0'}
j = []
for i in range(len(IDAX)):
    j += AX_BR[(IDAX[i])]
print(j)