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
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
按OP所需的方式获取输出的代码:
输出:
^{pr2}$如果你只想使用字典来获得分数和数值,可以使用以下方法。在
输出:
编辑:
如果列表中的等级存在重复值:
输出:
使用
enumerate
的代码:另一种解决方案是使用dict理解:
输出
^{pr2}$相关问题 更多 >
编程相关推荐