【问题标题】:Sort one list based on another array [duplicate]根据另一个数组对一个列表进行排序[重复]
【发布时间】:2020-09-08 08:57:40
【问题描述】:

我有一个数组:

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

另一个数组:

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

我可以像one 一样对two 进行排序吗?没有特定的顺序吗?我一直希望它订购为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)

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

【问题讨论】:

  • 它不一样,这就是我尝试过的。因为它正在订购不是我想要的压缩列表
  • 这两个列表是否总是包含相同的项目?为什么不直接复制列表?另外,“这是对压缩数组进行排序”是什么意思?你得到的输出与你想要的输出是什么?
  • 是什么阻止你做two[:] = one 左右?我不明白你在这里想要达到什么目的。您在寻找排序索引吗?

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


【解决方案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']

【讨论】:

  • 我是白痴还是说 new_list[a.index(x)]=x 不仅仅具有创建 a 副本的效果?
  • 这听起来像two[:] = one 甚至只是list(one) 的一种非常奇特的方式
  • @noob 如果这对你有用,请接受它作为正确答案
  • @MadPhysicist 难道你不知道开发人员的工作是编写代码,而不是解决问题吗?如果 wundermahn 为他们编写的每一行代码计费怎么办?
  • @Neil。虽然我的用户名只有 90% 准确(我已售罄并成为一名工程师),但我从未真正成为一名开发人员。但我听说过故事......
【解决方案2】:

除非我遗漏了什么,否则你在做什么,以及其他答案做什么,只是复制一个。

因此我建议更整洁:

three = [x for x in one]

【讨论】:

  • list(one)one.copy()one[:] 开头。很确定最后一个赢了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 2013-09-12
  • 2013-09-17
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
相关资源
最近更新 更多