我有一个字符串列表,像这样:
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结构,但我很好奇是否有更短的方法。有什么建议吗?
当前回答
你可以创建一个pandas Series,使用主列表作为数据,另一个列表作为索引,然后根据索引进行排序:
import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()
输出:
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
其他回答
这是一个老问题,但我看到的一些答案实际上并不能工作,因为zip是不可编写脚本的。其他答案没有费心导入operator,并在这里提供关于这个模块及其好处的更多信息。
对于这个问题,至少有两个好的习语。从您提供的示例输入开始:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
使用“装饰-排序-取消装饰”成语
这也被称为schwartzan_transform,得名于R. Schwartz,他在90年代在Perl中推广了这种模式:
# Zip (decorate), sort and unzip (undecorate).
# Converting to list to script the output and extract X
list(zip(*(sorted(zip(Y,X)))))[1]
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
注意,在本例中Y和X是按字典顺序排序和比较的。也就是说,比较第一项(来自Y);如果它们相同,则比较来自X的第二项,依此类推。这可能会创建不稳定的输出,除非您包含字典顺序的原始列表索引,以保持副本的原始顺序。
使用operator模块
这使您可以更直接地控制如何对输入进行排序,因此您可以通过简单地声明排序所依据的特定键来获得排序稳定性。点击这里查看更多示例。
import operator
# Sort by Y (1) and extract X [0]
list(zip(*sorted(zip(X,Y), key=operator.itemgetter(1))))[0]
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
Zip,按第二列排序,返回第一列。
zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]
另一种选择,结合了几个答案。
zip(*sorted(zip(Y,X)))[1]
为了在python3中工作:
list(zip(*sorted(zip(B,A))))[1]
我创建了一个更通用的函数,它根据另一个列表对两个以上的列表进行排序,灵感来自@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
我认为原题的题目不准确。如果你有两个条目数量相同的列表,并且列表1中的每个条目都以相同的顺序与列表2相关(例如a = 0, b = 1,等等),那么问题应该是“如何对字典排序?”',而不是'如何根据另一个列表的值对列表进行排序?'。在这种情况下,下面的解决方案是最有效的:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
dict1 = dict(zip(X,Y))
result = sorted(dict1, key=dict1.get)
print(result)
结果:
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']