Python:index()有问题吗?

2024-05-19 13:09:34 发布

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

我正在研究pyschools的事情,它让我很困惑。 代码如下:

def convertVector(numbers):
    totes = []
    for i in numbers:
        if i!= 0:
            totes.append((numbers.index(i),i))
    return dict((totes))

它应该以“稀疏向量”作为输入(例如:[1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0]) 并返回一个dict映射非零项到它们的索引。 因此带有0:12:1等的dict,其中x是列表中的非零项,y是其索引。在

所以对于示例编号,它想要这样:{0: 1, 9: 1, 2: 1, 4: 2, 6: 1} 但是相反,给我的是:{0: 1, 4: 2}(在它变成dict之前,它看起来是这样的: [(0, 1), (0, 1), (4, 2), (0, 1), (0, 1)]

我的计划是i遍历numbers,创建一个包含该数字及其索引的元组,然后将其转换为dict。代码看起来很简单,我不知所措。 在我看来,numbers.index(i)并没有返回索引,而是返回了其他一些不受怀疑的数字。在

我对index()的理解有缺陷吗?是否存在已知的index问题? 有什么想法吗?在


Tags: 代码inforindexreturnifdef数字
3条回答

你想做的,可以用一行来完成:

>>> dict((index,num) for index,num in enumerate(numbers) if num != 0)
{0: 1, 2: 1, 4: 2, 6: 1, 9: 1}

是的,你对list.index的理解是错误的。它查找列表中第一个与参数比较的第一个项的位置。在

要获取当前项的索引,您需要使用enumerate进行迭代:

for index, item in enumerate(iterable):
  # blah blah

index()只返回第一个:

>>> a = [1,2,3,3]
>>> help(a.index)
Help on built-in function index:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

如果您同时需要数字和索引,可以利用enumerate

^{pr2}$

并适当修改代码:

^{3}$

产生

>>> convertVector([1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0])
{0: 1, 9: 1, 2: 1, 4: 2, 6: 1}

[虽然,正如有人指出的那样,尽管我现在找不到它,但是比起通过列表,直接使用totes = {}编写并分配给它要容易得多。]

相关问题 更多 >