我在pyschools上做这件事,让我神秘莫测.这是代码:
def convertVector(numbers):
totes = []
for i in numbers:
if i!= 0:
totes.append((numbers.index(i),i))
return dict((totes))
Run Code Online (Sandbox Code Playgroud)
它应该采用'稀疏向量'作为输入(例如[1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0]:)并返回一个将非零条目映射到其索引的dict.所以带有0:1,2:1等的字典在哪里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,创建该数字及其索引的元组,然后将其转换为字典.代码似乎很简单,我很茫然.它只是看起来像是numbers.index(i)没有返回索引,而是返回一些其他未预料到的数字.
我对index()缺陷的理解是什么?有已知index问题吗?有任何想法吗?
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.
Run Code Online (Sandbox Code Playgroud)
如果你想要数字和索引,你可以利用enumerate:
>>> for i, n in enumerate([10,5,30]):
... print i,n
...
0 10
1 5
2 30
Run Code Online (Sandbox Code Playgroud)
并适当修改您的代码:
def convertVector(numbers):
totes = []
for i, number in enumerate(numbers):
if number != 0:
totes.append((i, number))
return dict((totes))
Run Code Online (Sandbox Code Playgroud)
哪个产生
>>> convertVector([1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0])
{0: 1, 9: 1, 2: 1, 4: 2, 6: 1}
Run Code Online (Sandbox Code Playgroud)
[虽然,正如有人指出的那样,虽然我现在找不到它,但是通过列表totes = {}来直接编写和分配它会更容易totes[i] = number.]