a = ['123b4', '234v5', 'lobf56']
b = [obj1, obj2, obj3] # where each obj is list of object which has attribute called 'serial' which matches serial numbers in list #a
其中obj1.serial为234v5,obj2.serial为lobf56,obj3.serial为123b4
tmplist=list()
for each in a:
for obj in b:
if each == obj.serial:
tmplist.append(obj)
print(tmplist)
输出:[obj3, obj1, obj2]
我目前能够通过上述方式实现排序。但是有更好的方法吗?
最佳答案
做 list comprehension有帮助吗?
[obj for each in a for obj in b if each == obj.serial]
如果比较两者之间的时间,您的方法是:
1.6 µs ± 25.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
列表理解需要:
1.37 µs ± 18.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
因此,如果“更好的方法”是指效率。这绝对重要。
关于python - 按属性值排序对象列表,属性值的顺序在另一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55545030/