以与引用列表相同的方式从相应列表中排序或删除元素



我有两个相同长度的python列表:

listA = [7,6,3,2,1,4,5]
listB = [a,b,c,d,e,f,g]

是他们对listA排序并以相同方式更改listB值的某种方式(可能是简单的函数)。意味着

listA_new = [1,2,3,4,5,6,7]

listB_new = [e,d,c,f,g,b,a]

关于删除重复项同样的问题。例如,如果我有一个列表

listC = [1,1,4,4,5,6,7] 

listD = [a,b,c,d,e,f,g]

结果应该是:

listC_new = [1,4,5,6,7]

listD_New = [a,c,e,f,g]

试试这个:

[i for j, i in sorted(zip(listA, listB))]

输出:

listA = [7, 6, 3, 2, 1, 4, 5]
listB = ["a", "b", "c", "d", "e", "f", "g"]
In [5]: [i for j, i in sorted(zip(listA, listB))]
Out[5]: ['e', 'd', 'c', 'f', 'g', 'b', 'a']

支持C和D(删除重复项):

sorted(list({j: i for j, i in reversed(sorted(zip(listC, listD)))}.values()))

.values()返回ListD:['a', 'c', 'e', 'f', 'g'],.keys()返回ListC:[1, 4, 5, 6, 7]

这可能对您有所帮助:如何以完全相同的方式对两个相互引用的列表进行排序

要删除重复项,可以使用:

ListA = [7,6,3,2,1,4,5]
mylist = list(dict.fromkeys(ListA))
ListB = [a,b,c,d,e,f,g]
mylist = list(dict.fromkeys(ListB))

关于"删除重复项";bit:您可以像另一个答案一样开始,但也可以通过dict管道压缩和排序列表。在Python 3中,dict将尊重插入顺序,但它将保留每个键的最后一个,因此您必须在排序时反转列表,然后在dict阶段后反转回来。

>>> listC = [1,1,4,4,5,6,7] 
>>> listD = ["a","b","c","d","e","f","g"]
>>> list(reversed(dict(sorted(zip(listC, listD), reverse=True)).items()))
[(1, 'a'), (4, 'c'), (5, 'e'), (6, 'f'), (7, 'g')]
>>> listC_new, listB_new = zip(*_)
>>> listC_new
(1, 4, 5, 6, 7)
>>> listB_new
('a', 'c', 'e', 'f', 'g')

第一部分

listA = [7,6,3,2,1,4,5]

listB = ['a','b','c','d','e','f','g']
dict_ = {key:value for key,value in zip(listB,listA)}
listA_new = sorted(listA)
listB_new = sorted(listB,key=lambda e:dict_[e])
print(listA_new)
print(listB_new)
<<编辑>输出/编辑>
[1, 2, 3, 4, 5, 6, 7]
['e', 'd', 'c', 'f', 'g', 'b', 'a']

对于不重复的项。试试这个。

listC = [1,1,4,4,5,6,7]

listD = ['a','b','c','d','e','f','g']

listC_out = []
listD_out = []
for a,b in zip(listC,listD):
if a not in listC_out:
listD_out.append(b)
listC_out.append(a)
print(listC_out)
print(listD_out)
<<编辑>输出/编辑>
[1, 4, 5, 6, 7]
['a', 'c', 'e', 'f', 'g']