python - 根据另一个数组对一个列表进行排序
问题描述
我有一个数组:
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']
推荐阅读
- python - 对 sklearn Pipeline Imputer 的列顺序感到困惑
- r - 使用 r 中的日期变量获取最近的观察结果
- c# - 如何在 C# 中使用 IHTTPClientFactory
- r - 为什么在 R 中使用 plotcounts 和 ggplot 绘制时,我的一个组织样本的 DEG 是单独绘制的?
- android - 知道应用程序内部的信息作为另一个类中的列表存在,我如何在颤振中使用搜索
- laravel - 将文件上传到 S3 时出错:PutObject 错误
- java - iText 1.4.8 支持 Html 标签转换
- kotlin - Kotlin MPP 期望/实际具有不同的签名
- xml - Powershell从文件中删除特定文本
- node.js - NodeJS 在数据库或属性文件中存储 mongo 聚合查询