返回非零值和相应索引位置的字典

2024-10-08 18:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了无数个小时看python字典教程,但仍然不知道如何返回所需的结果。在

给出了一些等级列表(0到1作为浮动),称为变量y
y = [0.0, 0.97, 0.0, 0.0, 0.0, 0.82, 0.66, 0.0, 0.0, 0.90, 0.0, 0.0]
我有一本字典叫dic
dic = {'pos':[ ], 'grds':[ ]}

我想返回列表中所有非零的分数和相应的位置作为字典dic,而不修改y列表。非常感谢协助解决,但也希望了解解决方案。在


Tags: pos列表字典教程解决方案分数小时dic
2条回答

按OP所需的方式获取输出的代码:

pos_grade = {'pos': [], 'grds': []}

y = [0.0, 0.97, 0.0, 0.0, 0.0, 0.82, 0.66, 0.0, 0.0, 0.90, 0.0, 0.0, 0.82]

for i, x in enumerate(y):
   if x != 0.0:
       pos_grade['pos'].append(i)
       pos_grade['grds'].append(x)

print pos_grade

输出:

^{pr2}$

如果你只想使用字典来获得分数和数值,可以使用以下方法。在

pos_grade = {}

y = [0.0, 0.97, 0.0, 0.0, 0.0, 0.82, 0.66, 0.0, 0.0, 0.90, 0.0, 0.0]

i = 0
for x in y:
   if x != 0.0:
       pos_grade[x] = i
   i += 1

print pos_grade

输出:

{0.9: 9, 0.97: 1, 0.66: 6, 0.82: 5}

编辑:

如果列表中的等级存在重复值:

from collections import defaultdict

pos_grade = defaultdict(list)

y = [0.0, 0.97, 0.0, 0.0, 0.0, 0.82, 0.66, 0.0, 0.0, 0.90, 0.0, 0.0, 0.82]

i = 0
for x in y:
   if x != 0.0:
       pos_grade[x].append(i)
   i += 1

print pos_grade

输出:

defaultdict(<type 'list'>, {0.9: [9], 0.97: [1], 0.66: [6], 0.82: [5, 12]})

使用enumerate的代码:

from collections import defaultdict

pos_grade = defaultdict(list)

y = [0.0, 0.97, 0.0, 0.0, 0.0, 0.82, 0.66, 0.0, 0.0, 0.90, 0.0, 0.0, 0.82]

for i, x in enumerate(y):
   if x != 0.0:
       pos_grade[x].append(i)

print pos_grade

另一种解决方案是使用dict理解:

y = [0.0, 0.97, 0.0, 0.0, 0.0, 0.82, 0.66, 0.0, 0.0, 0.90, 0.0, 0.0]
{v:k for k,v in enumerate(y) if v!=0}

输出

^{pr2}$

相关问题 更多 >

    热门问题