我有一个字符串列表,像这样:
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结构,但我很好奇是否有更短的方法。有什么建议吗?
当前回答
最短的代码
[x for _, x in sorted(zip(Y, X))]
例子:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Z = [x for _,x in sorted(zip(Y,X))]
print(Z) # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
一般来说
[x for _, x in sorted(zip(Y, X), key=lambda pair: pair[0])]
解释道:
压缩这两个列表。 使用sorted()根据zip文件创建一个新的排序列表。 使用列表推导式从已排序、压缩的列表中提取每对的第一个元素。
有关如何设置\use key参数以及一般的排序函数的更多信息,请参阅以下内容。
其他回答
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)))
list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]
output=[]
cur_loclist = []
获取list2中的唯一值
list_set = set(list2)
查找list2中索引的loc
list_str = ''.join(str(s) for s in list2)
索引在list2中的位置使用cur_loclist跟踪
[0, 3, 7, 1, 2, 4, 8, 5, 6]
for i in list_set:
cur_loc = list_str.find(str(i))
while cur_loc >= 0:
cur_loclist.append(cur_loc)
cur_loc = list_str.find(str(i),cur_loc+1)
print(cur_loclist)
for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)
一个简单的句子。
list_a = [5,4,3,2,1]
list_b = [1,1.5,1.75,2,3,3.5,3.75,4,5]
假设你想让列表a匹配列表b。
orderedList = sorted(list_a, key=lambda x: list_b.index(x))
当需要将较小的列表与较大的列表进行排序时,这是很有用的。假设较大的列表包含较小列表中的所有值,就可以做到这一点。
把两个列表压缩在一起,排序,然后取你想要的部分:
>>> yx = zip(Y, X)
>>> yx
[(0, 'a'), (1, 'b'), (1, 'c'), (0, 'd'), (1, 'e'), (2, 'f'), (2, 'g'), (0, 'h'), (1, 'i')]
>>> yx.sort()
>>> yx
[(0, 'a'), (0, 'd'), (0, 'h'), (1, 'b'), (1, 'c'), (1, 'e'), (1, 'i'), (2, 'f'), (2, 'g')]
>>> x_sorted = [x for y, x in yx]
>>> x_sorted
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
把这些结合起来得到:
[x for y, x in sorted(zip(Y, X))]
我认为原题的题目不准确。如果你有两个条目数量相同的列表,并且列表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']