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

标签 python dictionary

我花了无数个小时观看 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/

相关文章:

swift - 将函数映射到全局变量中快速错误 "Initializer ' init(_ : )' requires that ' [_ ]' conform to ' LosslessStringConvertible'"

Python:如何根据键值对对字典进行分组

python - 创建元组时迭代字典

python - 如果你使用 wheel 格式发布 Python,你还需要将它们发布为 egg 吗?

python - ExponentialSmoothing - 该日期图使用什么预测方法?

python - 对于可能返回 None 的方法,哪种返回方式是 "better"?

python - 需要缩短get函数

python - 使用 Expat 在 Python 中解析 XML

python - 如何从具有值列表的字典列表中形成 DataFrame?

javascript - React js 组件, map 有效,foreach 无效