如何排序一个项目以匹配另一个项目,但在其他地方应用排序?

2024-10-04 01:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

比如说我有单词和任意字符串

LEAST HDKEN

现在说我重新安排最少的偷。我想对第二个词用同样的“变换”

STEAL ENDKH

因此,由于L(第一个字符)至少到达了STEAL的末尾,因此字符串(H)的第一个字符也到达了end位置。其他的也一样


Tags: 字符串字符单词endleast末尾词用steal
1条回答
网友
1楼 · 发布于 2024-10-04 01:35:47

把这两条线拉在一起,这样你就可以把成对的字母排序了。然后排序,然后解压缩

>>> zip(*sorted(zip('LEAST', 'HDKEN'), key=lambda s:'STEAL'.index(s[0])))
[('S', 'T', 'E', 'A', 'L'), ('E', 'N', 'D', 'K', 'H')]

或者,再长一点:

# Make pairs of letters
pairs = zip('LEAST', 'HDKEN')
# Sort pairs, using the index into STEAL as the sort key
sortedpairs = sorted(pairs, key=lambda s:'STEAL'.index(s[0]))
# Unzip the pairs back into words
result = zip(*sortedpairs)
# Print the words
print ''.join(result[0]), ''.join(result[1])

(根据需要打印STEAL ENDKH

相关问题 更多 >