gpt4 book ai didi

python - 通过单词的拼写来排序字典 - Python 3

转载 作者:行者123 更新时间:2023-11-30 22:48:16 25 4
gpt4 key购买 nike

我想知道是否有人知道如何制作一本按特定单词的拼写排序的字典?由于字典是未排序的,因此我求助于 OrderedDict,但我相信您只能通过键和值对其进行排序。知道如何以这种方式订购吗?

这是我正在从事的项目的一部分:

word = input("word")
list_1 = list(word)

word>? apple

len_list_1 = len(list_1)


dict = {}

for x in range(0, len(list_1)):
dict[list_1[x]] = list_1.count(list_1[x])

print(dict)

>{'l': 1, 'p': 2, 'a': 1, 'e': 1}

我试图保持它的单词“apple”的顺序,然后以某种方式将字典转换为纯文本:

{'a' : 1, 'p': 2, 'l': 1, 'e': 1}
> a1p2l1e1 #as my final answer

最佳答案

首先,请注意,您的代码是一种非常低效且不符合 Python 的方式来完成非常简单的事情:

>>> from collections import Counter
>>> Counter('apple')
Counter({'p': 2, 'a': 1, 'e': 1, 'l': 1})

(效率低下,因为你每次都计算每个字母,例如 'aaaaa' 会计算 'a' 5 次;unpythonic,因为你声明并且不使用长度变量并使用 range(len (...)) 这几乎从来都不是一个好主意。)

然后您可以对此计数器进行排序,并将其设为 OrderedDict。我按单词中的第一次出现进行排序:

>>> word = 'apple'
>>> c = Counter(word)
>>> OrderedDict(sorted(c.items(), key=lambda x: word.index(x[0])))
OrderedDict([('a', 1), ('p', 2), ('l', 1), ('e', 1)])

请注意,如果您只是对字母进行分组,答案将会非常不同:如果您想做 'b1o1b1' 之类的事情,字典不是正确的数据结构。

如果您想要的输出只是字符串'a1p2l1e1',您可以执行以下操作:

>>> word = 'apple'
>>> c = Counter(word)
>>> sorted_letter_counts = sorted(c.items(), key=lambda x: word.index(x[0]))
>>> ''.join(c + str(n) for c,n in sorted_letter_counts)
'a1p2l1e1'

或者作为一句台词:

>>> word = 'apple'
>>> ''.join(c + str(n) for c,n in sorted(Counter('apple').items(), key=lambda x: word.index(x[0])))
'a1p2l1e1'

关于python - 通过单词的拼写来排序字典 - Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40244804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com