如何在其原始列表中跟踪元素计数和最后一个索引?
我需要一种非常有效的方法来迭代列表,并将其元素作为字典键,并将它们的计数和最后位置作为大小为 2 的列表中的值。
例如,列表 [1,1,1,2] 必须生成字典 {1:[3,2], 2:[1,3]}。
我期望这段代码能够工作:
myList = [1,1,1,2,2,2,3,4,5,5,6,7]
myDict = dict.fromkeys(myList, [0,0])
for i, e in enumerate(myList):
print(i, e)
myDict[e][0] += 1
myDict[e][1] = i
print(myDict)
但它的输出
{1: [12, 11], 2: [12, 11], 3: [12, 11], 4: [12, 11], 5: [12, 11], 6: [12, 11], 7: [12, 11]}
不是
{1: [3, 2], 2: [3, 5], 3: [1, 6], 4: [1, 7], 5: [2, 9], 6: [1, 10], 7: [1, 11]}
我没想到的,因为我认为迭代变量(即)是“通常”变量,因此我期望分配它们的“副本”,而不是分配引用就像列表的情况一样。
如何解决这个问题呢?
I need a very efficient way to iterate over a list and put its element as a dictionary keys and their count and last position as values in a list of size two.
For example, the list [1,1,1,2] must produce the dictionary {1:[3,2], 2:[1,3]}.
I expected this code to work:
myList = [1,1,1,2,2,2,3,4,5,5,6,7]
myDict = dict.fromkeys(myList, [0,0])
for i, e in enumerate(myList):
print(i, e)
myDict[e][0] += 1
myDict[e][1] = i
print(myDict)
But its output is
{1: [12, 11], 2: [12, 11], 3: [12, 11], 4: [12, 11], 5: [12, 11], 6: [12, 11], 7: [12, 11]}
instead of
{1: [3, 2], 2: [3, 5], 3: [1, 6], 4: [1, 7], 5: [2, 9], 6: [1, 10], 7: [1, 11]}
I did not expect this, because I considered iteration variables (i,e) as "usual" variables and therefore I expected a "copy" of them to be assigned, not a reference like it would happen in case of lists.
How to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该问题来自您的
dict.fromkeys(...)
调用。它将相同对象[0,0]
分配给所有键,而不是该对象的副本。解决方案是将输出字典初始化为空字典。然后在循环中,首先检查该键是否已在字典中。如果没有,则使用
[0,0]
初始化新密钥,否则执行增量和索引更新,就像您在代码中所做的那样。The issue comes from your
dict.fromkeys(...)
call. It is assigning the same object[0,0]
to all keys, not a copy of this object.The solution is to initialize your output dictionary as an empty dictionary. Then in your loop, first check if the key is already in the dictionary or not. If not then initialize the new key with
[0,0]
, else perform the increment and index update as you already do in your code.我认为这会很快 - 使用计数器来获取出现的数量,并在其中获得最高的INEDEX。
输出
I would assume this would be pretty fast - use a counter to get the number of occurrences and max/np.where to get the highest inedex.
Output