- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道是否有人知道如何制作一本按特定单词的拼写排序的字典?由于字典是未排序的,因此我求助于 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/
我想通过用语言环境拼写数字来本地化数字,最后使用了 ICU4J。我在许多地区都取得了成功,但似乎没有在格鲁吉亚、土耳其或阿拉伯语等地区完成。 ULocale locale = new ULocale(
我正在研究具有端点的 swagger API 规范: /authorizations 我也想为这个端点定义一个替代拼写(授权)。这可能吗?或者我是否需要为每个拼写定义一个单独的路由? /authori
我正在研究具有端点的 swagger API 规范: /authorizations 我也想为这个端点定义一个替代拼写(授权)。这可能吗?或者我是否需要为每个拼写定义一个单独的路由? /authori
我使用 Yahoo BOSS 的时间很短。这是一个简单的搜索 API,但拼写建议支持确实不那么强大。周围的人是否有任何关于在 BOSS 上获得更好的拼写建议的想法。 最佳答案 不幸的是,甚至在几年后,
问题如下:我正在编写一个强力解密器来破解一些 super secret 代码(这是一场竞赛,而不是犯罪),结果证明这是不可能的:树中的节点太多需要被搜查。为了克服这个问题,我认为检查中间“解决方案”以
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 8 年前。 Improve this qu
我是一名优秀的程序员,十分优秀!