按照参考数组对对象数组进行排序
创始人
2024-08-23 13:00:42
0

假设有一个由对象组成的数组以及一个参考数组,需要根据参考数组中元素的顺序对对象数组进行排序,步骤如下:

  1. 对参考数组进行去重:
reference_array = list(set(reference_array))
  1. 为对象数组中的每个对象添加一个序号属性,该属性的值在参考数组中的索引值加1(这里加1是为了与python中列表的索引值保持一致):
for obj in obj_array:
    obj.index = reference_array.index(obj.name) + 1
  1. 对对象数组进行排序:
sorted_array = sorted(obj_array, key=lambda obj: obj.index)

完整代码示例:

# define class for object
class Obj(object):
    def __init__(self, name):
        self.name = name

# initialize object and reference arrays
obj_array = [Obj('B'), Obj('C'), Obj('D'), Obj('A')]
reference_array = ['A', 'B', 'C', 'D', 'A']

# remove duplicates from reference array
reference_array = list(set(reference_array))

# add index to each object based on reference array
for obj in obj_array:
    obj.index = reference_array.index(obj.name) + 1

# sort object array based on index
sorted_array = sorted(obj_array, key=lambda obj: obj.index)

# print sorted object array
for obj in sorted_array:
    print(obj.name)

相关内容

热门资讯

透视总结!wpk免费辅助,wp... 透视总结!wpk免费辅助,wpk辅助软件(透视)总是有透视神器(哔哩哔哩)1、wpk辅助软件公共底牌...
透视阶段!德州局透视脚本免费版... 透视阶段!德州局透视脚本免费版下载手机版,约局吧如何查看是否有挂(透视)好像有挂(哔哩哔哩)1、德州...
透视积累!hhpoker的辅助... 透视积累!hhpoker的辅助是真的吗,hhpoker真的假的(透视)真是真的是有透视器(哔哩哔哩)...
透视策略!wepoker有没有... 透视策略!wepoker有没有机器人,wepoker辅助器安装包(透视)切实有挂(哔哩哔哩)1、超多...
透视积累!hhpoker外开挂... 透视积累!hhpoker外开挂靠谱吗,wepoker软件安装包(透视)确实是真的脚本器(哔哩哔哩)1...
透视指南!hhpoker德州机... 透视指南!hhpoker德州机器人,wpk透视辅助靠谱吗(透视)本来是真的挂(哔哩哔哩)wpk透视辅...
透视秘籍!德普之星有辅助软件吗... 透视秘籍!德普之星有辅助软件吗,德扑圈透视挂(透视)一贯有脚本挂(哔哩哔哩)德普之星有辅助软件吗能透...
透视绝活!wepoker破解工... 透视绝活!wepoker破解工具,pokernow辅助工具(透视)都是有挂(哔哩哔哩)1、poker...
透视教程书!wpk透视辅助,w... 透视教程书!wpk透视辅助,wpk作必弊最怕三个东西(透视)果然是真的透视攻略(哔哩哔哩)1、任何w...
透视资料!aapoker怎么控... 透视资料!aapoker怎么控制牌,拱趴大菠萝自动计算机器人(透视)其实是真的挂(哔哩哔哩)1、玩家...