如果我有一个单词列表,例如
words = ['apple', 'boat', 'cat']
我还有一个数字列表,例如
num = [1, 2, 0]
有没有办法根据第二个列表中的数字对第一个列表进行排序? IE。 'apple' 的索引是 0,所以它应该在列表的最后,'boat' 的索引是 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)))
