如何记录在python中对一个字符串使用排序时发生的事情的历史,并将其应用于其他字符串


with open(sys.argv[1]) as f:
lst = list(f.readline().strip())
sortedLst = sorted(lst, key = lambda x: (x.lower(), x.swapcase()))
print(lst)
print(sortedLst)

我举的一个例子是"ThatCcer"。对于lst,我的输出是[TOT','h','a','T','C','C','e','r'],而对于sortedLst,我的输出来是['a','C','C','e','h','r','T','T']。

这正是我想要的——按照字母顺序对单词进行排序,小写字母优先于大写字母。

我试图实现的是通过按照我对ThatCher进行排序的方式对其他8个字母的输入进行匹配。我将如何实现这一目标?

编辑:我被告知这个问题不清楚——我很抱歉,但有点难以解释,所以我会再试一次。

通过将ThatCcer排序为acCehrtT,lst[0]('T'(占据sortedLst[7]的位置,lst[1]('h'(占据sortedLst[4]的位置,依此类推…

这是我想要记录的历史记录,这样给定的任何其他字符串都可以复制"ThatCcer"所采取的步骤,例如:s = ['h', 'o', 'w', 'e', 'v', 'e', 'r', 's']我希望s[0]在sortedS[7]中采取其"位置,就像ThatCer所做的那样。

我希望这能让它更清楚一点!

IIUC,您希望实现类似于numpy.argsort的行为。

你可以根据你的标准对一个范围进行排序,并使用它来重新索引任何字符串:

lst =  ['T', 'h', 'a', 't', 'C', 'c', 'e', 'r']
idx = list(range(len(lst)))
sorted_idx = sorted(idx, key=lambda x: (lst[x].lower(), lst[x].swapcase()))
# [2, 5, 4, 6, 1, 7, 3, 0]
# now use the index to sort
[lst[i] for i in sorted_idx]
# ['a', 'c', 'C', 'e', 'h', 'r', 't', 'T']
# keep the same order on another string
lst2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
[lst2[i] for i in sorted_idx]
# ['c', 'f', 'e', 'g', 'b', 'h', 'd', 'a']

使用zip的另一种方法:

lst =  ['T', 'h', 'a', 't', 'C', 'c', 'e', 'r']
lst2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list(zip(*sorted(zip(lst, lst2), key=lambda x: (x[0].lower(), x[0].swapcase()))))
# or as individual lists
# (lst_sorted, lst2_sorted) = list(zip(*sorted(zip(lst, lst2),
#                               key=lambda x: # (x[0].lower(), x[0].swapcase()))))

输出:

[('a', 'c', 'C', 'e', 'h', 'r', 't', 'T'),
('c', 'f', 'e', 'g', 'b', 'h', 'd', 'a')]

根据字符串字符对枚举字符串进行排序,然后将(排序(索引和字符分开;使用operator.itemgetter创建可重用的可调用项。

import operator
def f(thing):
s_lst = sorted(enumerate(thing),key = lambda x: (x[1].lower(), x[1].swapcase()))
argsort = operator.itemgetter(*[x[0] for x in s_lst])
s_lst = [x[1] for x in s_lst]
return s_lst,argsort

>>> s_lst, argsort = f('ThatCcerCTaa')
>>> s_lst
['a', 'a', 'a', 'c', 'C', 'C', 'e', 'h', 'r', 't', 'T', 'T']
>>> argsort('ThatCcerCTaa')
('a', 'a', 'a', 'c', 'C', 'C', 'e', 'h', 'r', 't', 'T', 'T')
>>> argsort
operator.itemgetter(2, 10, 11, 5, 4, 8, 6, 1, 7, 3, 0, 9)
>>>

相关内容

最新更新