【问题标题】:Can you manually sort a list in python?您可以在python中手动对列表进行排序吗?
【发布时间】:2014-03-05 18:07:31
【问题描述】:

如果我有一个单词列表,例如

words = ['apple', 'boat', 'cat']

我还有一个数字列表,例如

num = [1, 2, 0]

有没有办法根据第二个列表中的数字对第一个列表进行排序? IE。 'apple'的索引是0,所以应该排在最后,'boat'的索引是1,所以应该排在第一位,以此类推

【问题讨论】:

  • 第三个答案真的很有趣,使用itemgetter()
  • 为什么最后一个是 0?这是非常非程序化的 =)

标签: python list sorting indexing


【解决方案1】:
words = ['apple','boat','cat']
num = [1,2,0]
print([words[current_index] for current_index in num])

输出

['boat', 'cat', 'apple']

列表推导方法适用于 Python 2.x 和 3.x。

虽然我会推荐这个,但你可以像这样更简洁地写这个

print(map(words.__getitem__, num))

同样的东西可以用 Python 3.x 来写,像这样

print(list(map(words.__getitem__, num)))

【讨论】:

  • 啊!简单的列表理解:)
  • 哇,这比 NumPy arg 索引还要快
【解决方案2】:

使用operator.itemgetter

>>> words = ['apple','boat','cat']
>>> num = [1,2,0]
>>> import operator
>>> operator.itemgetter(*num)(words)
('boat', 'cat', 'apple')

【讨论】:

    【解决方案3】:

    由于您知道索引不会在第二个列表中重复,并且您知道它们的长度相同,因此您可以创建一个 for 循环:

    words_b = []
    for n in num:
        words_b.append(words[n])
    words = words_b
    

    但是thefourtheye 已经以更紧凑的方式做到了这一点。如果您不精通 Python,这只是更具可读性。

    【讨论】:

    • 哎呀,小错误——已修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2013-10-12
    • 1970-01-01
    • 2023-01-11
    • 2022-12-03
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多