我花了无数个小时观看 python 字典教程,但仍然不知道如何返回所需的结果。
给定一些名为变量 y
的成绩列表(0 到 1 作为 float )。
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
列表。非常感谢您对解决问题的帮助,但也想了解解决方案。
最佳答案
按照 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
输出:
{'grds': [0.97, 0.82, 0.66, 0.9, 0.82], 'pos': [1, 5, 6, 9, 12]}
<小时/>
如果只想使用字典来获取成绩和数值,可以使用以下方法。
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]})
<小时/>
使用枚举
的代码:
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
关于python - 字典 - 返回非零值和相应的索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293900/