0

我正在尝试使用最简单的方法来计算所有出现的 x 字典但没有结果。我不能导入任何库,也不能使用其他语句:for var in, if x, if not, if is。

脚本的结果应如下所示: 示例:

list = [1,2,1,'a',4,2,3,3,5,'a',2]

code

print occurrences(list)

result

1 = [0, 2]
2 = [1, 5, 10]
a = [3, 9]
and so on

@edited 更正的文本

4

2 回答 2

4
>>> l = [1,2,1,'a',4,2,3,3,5,'a',2]
>>> pos = {}
>>> for i, n in enumerate(l):
...     pos.setdefault(n, []).append(i)
... 
>>> pos
{'a': [3, 9], 1: [0, 2], 2: [1, 5, 10], 3: [6, 7], 4: [4], 5: [8]}
>>> for k, v in pos.items():
...     print "%s = %s" % (k, v)
... 
a = [3, 9]
1 = [0, 2]
2 = [1, 5, 10]
3 = [6, 7]
4 = [4]
5 = [8]
于 2012-10-23T14:42:16.460 回答
0

好的,不使用任何库或函数:

lis = [1,2,1,'a',4,2,3,3,5,'a',2]
dic={}
index=0
for item in lis:
    if item in dic:
        dic[item]+=[index]
        index+=1
    else:
        dic[item]=[index] 
        index+=1
print dic   

输出:

{'a': [3, 9], 1: [0, 2], 2: [1, 5, 10], 3: [6, 7], 4: [4], 5: [8]}
于 2012-10-23T14:51:36.383 回答