我有一个字符串列表,像这样:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
使用Y中的值对X进行排序以得到以下输出的最短方法是什么?
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
具有相同“键”的元素的顺序并不重要。我可以使用for结构,但我很好奇是否有更短的方法。有什么建议吗?
我有一个字符串列表,像这样:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
使用Y中的值对X进行排序以得到以下输出的最短方法是什么?
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
具有相同“键”的元素的顺序并不重要。我可以使用for结构,但我很好奇是否有更短的方法。有什么建议吗?
当前回答
我认为如果两个列表的大小不同或包含不同的项目,上面的大多数解决方案都是无效的。下面的解决方案很简单,应该可以解决这些问题:
import pandas as pd
list1 = ['B', 'A', 'C'] # Required sort order
list2 = ['C', 'A'] # Items to be sorted according to list1
result = pd.merge(pd.DataFrame(list1), pd.DataFrame(list2))
print(list(result[0]))
输出:
['A', 'C']
注意:任何不在list1中的项都将被忽略,因为算法不知道要使用的排序顺序。
其他回答
More_itertools有一个并行排序可迭代对象的工具:
鉴于
from more_itertools import sort_together
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Demo
sort_together([Y, X])[1]
# ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
Zip,按第二列排序,返回第一列。
zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]
我创建了一个更通用的函数,它根据另一个列表对两个以上的列表进行排序,灵感来自@Whatang的答案。
def parallel_sort(*lists):
"""
Sorts the given lists, based on the first one.
:param lists: lists to be sorted
:return: a tuple containing the sorted lists
"""
# Create the initially empty lists to later store the sorted items
sorted_lists = tuple([] for _ in range(len(lists)))
# Unpack the lists, sort them, zip them and iterate over them
for t in sorted(zip(*lists)):
# list items are now sorted based on the first list
for i, item in enumerate(t): # for each item...
sorted_lists[i].append(item) # ...store it in the appropriate list
return sorted_lists
下面是Whatangs的答案,如果你想获得两个排序的列表(python3)。
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Zx, Zy = zip(*[(x, y) for x, y in sorted(zip(Y, X))])
print(list(Zx)) # [0, 0, 0, 1, 1, 1, 1, 2, 2]
print(list(Zy)) # ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
记住Zx和Zy是元组。 我也在想是否有更好的方法来做到这一点。
警告:如果你用空列表运行它,它会崩溃。
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
你可以用一行写出来:
X, Y = zip(*sorted(zip(Y, X)))