根据另一个数组对一个列表进行排序

时间:2020-05-21 16:39:12

标签: python arrays python-3.x list sorting

我有一个数组:

one = ['telephone', 'first_name', 'second_name']

另一个数组:

two = ['first_name', 'second_name', 'telephone']

我可以像two一样对one进行排序吗?没有特别的顺序吗?我一直希望它以one

的形式订购

此功能:

def sort_list(list1, list2): 
    zipped_pairs = zip(list2, list1) 
    z = [x for _, x in (zipped_pairs)]    
    return z 

three = sort_list(two, one)

这是对我不想要的压缩数组进行排序

2 个答案:

答案 0 :(得分:1)

下面的sort_list函数应该可以解决问题

# Declare lists from OP example
one = ['telephone', 'first_name', 'second_name']
two = ['first_name', 'second_name', 'telephone']

# Sorting function
def sort_list(a,b):
    # If lists one and two arent of equal size, quit
    if (len(a) != len(b)):
        print("Lengths do not match. Exiting")
        return
    # Otherwise...
    else:
        # Create a new temp list equal to the sizeof one and two
        new_list = [None] * len(a)
        # Loop through the second list
        for x in b:
            # For each object, find where its index is in list one, and set that as the new index for temp list
            new_list[a.index(x)] = x

    # Return the temp list
    return new_list

# Print out before
print("Before: {}".format(two))
# Sort list two
two = sort_list(one, two)
# Print out after
print("After: {}".format(two))

收益:

Before: ['first_name', 'second_name', 'telephone']
After: ['telephone', 'first_name', 'second_name']

答案 1 :(得分:0)

除非我丢失了某些东西,否则您只是在做一个副本。

因此,我建议整洁:

three = [x for x in one]
相关问题