以下是一个使用Python的解决方法,按照相同的索引对两个列表进行排序:
def sort_lists_by_index(list1, list2):
# 检查两个列表的长度是否相等
if len(list1) != len(list2):
return "两个列表的长度不相等"
# 创建一个索引列表,用于排序
index_list = list(range(len(list1)))
# 使用索引列表对两个列表进行排序
sorted_list1 = [x for _,x in sorted(zip(index_list, list1))]
sorted_list2 = [x for _,x in sorted(zip(index_list, list2))]
return sorted_list1, sorted_list2
# 测试示例
list1 = [3, 1, 4, 2]
list2 = ['c', 'a', 'd', 'b']
sorted_list1, sorted_list2 = sort_lists_by_index(list1, list2)
print(sorted_list1) # 输出 [1, 2, 3, 4]
print(sorted_list2) # 输出 ['a', 'b', 'c', 'd']
在这个解决方法中,我们首先检查两个列表的长度是否相等。然后,我们创建一个索引列表,该列表的元素是从0到n-1的整数,其中n是列表的长度。接下来,我们使用zip()
函数将索引列表和原始列表进行配对,然后使用sorted()
函数对配对的元组进行排序。最后,我们使用列表推导式将排序后的元素提取出来,得到两个排序后的列表。
上一篇:按照特定的行数R分配唯一编号
下一篇:按照一个键对对象数组进行排序