py 2.7。我有一本列表字典。每个周期每个列表都会被其自身的新更新版本覆盖。
我正在使用第三方粒子系统。我正在做的是将每个键作为粒子的索引号,列表是它的位置和之前的位置。
但是当一个粒子“死亡”时,粒子的索引都会发生变化。当一个新的粒子与死粒子具有相同的索引时,一个键将被错误地覆盖。我想用死粒子的位置来保存那个键。
这是现在的代码:
if frame == 0:
branches = {}
...
for p in xrange(particle_count):
xp = emitter.GetParticle(p) #xp = current particle
trail = []
index = xp.GetIndex()
trail_length = xp.GetCustomDataCount() #number of previous positions
for i in xrange(trail_length):
previous_position = xp.GetCustomData(i)
trail.append(previous_position)
branches [index] = trail
我正在考虑将每个列表的第一个元素与它试图覆盖的列表的第一个元素进行比较。然后,如果不同,则将索引号加 1,直到有空位为止...?
编辑 - 我取得了进一步的进展并确定了我需要做什么,但不了解 python。这是一些新代码:
for p in xrange(particle_count):
xp = emitter.GetParticle(p) #xp = current particle
trail = []
index = xp.GetIndex()
trail_length = xp.GetCustomDataCount()
for i in xrange(trail_length):
previous_position = xp.GetCustomData(i)
trail.append(previous_position)
if index in branches:
this_trail = trail[0]
set_trail = branches[index]
set_trail = set_trail[0]
if this_trail == set_trail:
branches[index] = trail
else:
for b in branches:
set_trail = branches[b]
set_trail = set_trail[0]
if this_trail == set_trail:
branches[index] = trail
break
else:
branches[index] = trail
问题:当我说“if index in branches..”时,我正在检查每个条目是否匹配。如果轨迹相同,则旧的将被新的覆盖。但是,如果索引确实存在于字典中,但与条目不同,则不会发生任何事情。这是我需要的:
if index in branches:
this_trail = trail[0]
set_trail = branches[index]
set_trail = set_trail[0]
if this_trail == set_trail:
branches[index] = trail
else:
check all entries for a match(like i currently do)
if match, overwrite entry
if no match, add entry to a non-existing key
else:
branches[index] = trail
最佳答案
好的,我想我明白你的问题了,你的代码假设字典是有序的,但它们不是,它们有任意顺序,实际顺序实际上取决于字典的插入和删除历史以及具体的python实现。
你不应该依赖你的字典被排序,如果你想在你的字典中排序,你可以尝试使用 collections.OrderedDict
.
它们类似于普通词典,不同之处在于它们保留了其中元素的顺序。示例 -
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d[1] = 2
>>> d[5] = 10
>>> d[2] = 11
>>>
>>> d
OrderedDict([(1, 2), (5, 10), (2, 11)])
虽然您可能想重新考虑字典是否是您要使用的实际数据结构。如果你的索引是纯数字,你最好使用一个简单的列表。如果它们是 (x,y)
坐标的元组,您可以为此使用二维列表。
关于python - 根据元素添加/覆盖字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31633738/