我有一个数组:
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)
这是我不需要的压缩数组排序
下面的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']
除非我丢失任何东西,您在做什么,其他答案在做什么,只需复制a。
因此,我建议更整洁:
three = [x for x in one]