在 Python 中组织随机对象列表
所以我有一个列表,我想将其转换为包含每组对象的列表的列表。
IE ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] 会回来 [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']]
目前这就是我使用的:
givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4']
trgList = []
objNames = []
for val in givenList:
obj = val.split('.')[0]
if obj in objNames:
id = objNames.index(obj)
trgList[id].append(val)
else:
objNames.append(obj)
trgList.append([val])
#print trgList
当原始列表有大约 100,000 时,它似乎运行得不错ids...但我很好奇是否有更好的方法来做到这一点。对象或属性的顺序并不重要。有什么想法吗?
So I have a list that I want to convert to a list that contains a list for each group of objects.
ie
['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4']
would return
[['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']]
currently this is what I use:
givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4']
trgList = []
objNames = []
for val in givenList:
obj = val.split('.')[0]
if obj in objNames:
id = objNames.index(obj)
trgList[id].append(val)
else:
objNames.append(obj)
trgList.append([val])
#print trgList
It seems to run a decent speed when the original list has around 100,000 ids... but I am curious if there is a better way to do this. Order of the objects or attributes does not matter. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这需要更好地定义:当没有财产时你会做什么?您希望最终的列表按什么顺序排列?重复的怎么办?
通用算法是使用多重映射:每个键具有多个值的映射。
然后,您将扫描原始列表,将每个元素分成“对象”和“属性”,然后为对象和属性添加键值对。在此周期结束时,您将获得从对象到属性集的映射。然后您可以对此进行迭代以构建最终列表。
您可以使用第三方多重映射或通过映射到序列来自行实现。
当对象没有属性时,您可能需要创建一个虚拟属性。
This needs to be better defined: what do you do when there is no property? What order do you want the final list as? What about duplicates?
A general algorithm would be to use a multi-map: a map that has multiple values per key.
You will then scan through the original list, separate each element into an "object" and "property", and then add a key-value pair for the object and property. At the end of this cycle, you will have a mapping from objects to set of properties. You can then iterate over this to build your final list.
You can use a third-party multimap or implement yourself by mapping into a sequence.
You might want to create a dummy property for cases when the object does not have a property.