Python 中 enumerate 和 dict 的奇怪响应

问题描述 投票:0回答:2

使用

dict(enumerate(x))
,我们得到
{ (index, value) }
。相反,我需要
{ (value, index) }
。 所以,我写了这段代码......

idx= { n:i for i, n in enumerate(x)}

它适用于某些输入,但适用于其他输入则失败。 这是失败的输入。

x= [73,74,75,71,69,72,76,73]

,为什么会失败?应该做什么?

python list dictionary enumerate
2个回答
0
投票

73
在向量
x= [73,74,75,71,69,72,76,73]
中包含两次,这会导致歧义(相同的键对应于两个不同的索引值。)


0
投票

为什么会失败?

我们知道:

x = [73,74,75,71,69,72,76,73, 99]  # note the additional list item

结果:

{73: 7, 74: 1, 75: 2, 71: 3, 69: 4, 72: 5, 76: 6, 99: 8}

至少对于字典中的第一个键来说是 “坏”。它不好的原因(正如其他人指出的那样)是列表中存在重复的条目

x
,当我们处理它们时,我们在概念上正在做:

idx = {}
idx[73] = 0
idx[73] = 7
print(idx)

应该做什么?

我们不知道您对

73
键的实际期望是什么。我认为您很有可能想要值
0
,但也许您想要值
[0, 7]
在原始列表中显示
73
的两个索引。

另一个问题是不知道如何为附加项

99
(在重复的
73
之后出现)分配一个值。我们是否保留现有的索引条目
8
,还是希望它成为新的
7
,有效地替换重复项?

确定如何获得其他结果相当简单,我将向您提供一些可以尝试的方法。

选项1:

idx_expected = {73: 0, 74: 1, 75: 2, 71: 3, 69: 4, 72: 5, 76: 6, 99: 8}
idx_actual = {}
for index, value in enumerate(x):
    if value not in idx_actual:
        idx_actual[value] = index
print(idx_actual == idx_expected)

选项2:

## -------------
idx_expected = {73: 0, 74: 1, 75: 2, 71: 3, 69: 4, 72: 5, 76: 6, 99: 7}
idx_actual = {n:i for i, n in enumerate(dict.fromkeys(x))}
print(idx_actual == idx_expected)
## -------------

选项3:

## -------------
idx_expected = {73: [0, 7], 74: [1], 75: [2], 71: [3], 69: [4], 72: [5], 76: [6], 99: [8]}
idx_actual = {}
for index, value in enumerate(x):
    idx_actual.setdefault(value, []).append(index)
print(idx_actual == idx_expected)
## -------------
© www.soinside.com 2019 - 2024. All rights reserved.