我有以下OrderedDict
:
OrderedDict([('r', 1), ('s', 1), ('a', 1), ('n', 1), ('y', 1)])
实际上,这表示单词中字母的出现频率。
第一步-我将使用最后两个元素来创建一个这样的联合元组;
pair1 = list.popitem()
pair2 = list.popitem()
merge_list = (pair1[0],pair2[0])
new_pair = {}
new_pair[merge_list] = str(pair1[1] + pair2[1])
list.update(new_pair);
这为我创建了以下OrderedList:
OrderedDict([('r', 1), ('s', 1), ('a', 1), (('y', 'n'), '2')])
我现在想遍历元素,每次取后三个,并根据值的较低和确定什么是联合对象。
例如,上面的列表将变为;
OrderedDict([('r', 1), (('s', 'a'), '2'), (('y', 'n'), '2')])
但是上面是:
OrderedDict([ ('r', 1), ('s', 2), ('a', 1), (('y', 'n'), '2')])
结果将是:
OrderedDict([('r', 1), ('s', 2), (('a','y', 'n'), '3')])
因为我希望剩下的值较小
我尝试自己做,但不了解如何从OrderedDict到头再进行迭代。
我该怎么做?
已编辑
回答评论:
我得到一个句子中字母出现频率的字典:
{ 's':1, 'a':1, 'n':1, 'y': 1}
并需要从中创建一个霍夫曼树。
例如:
((s,a),(n,y))
我正在使用python 3.3
python大神给出的解决方案
简单的例子
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
for key, value in d.items():
print key, value
输出:
a 1
b 2
c 3
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
Python:同时在for循环中添加到列表列表 - python我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…
如何在Matplotlib条形图后面绘制网格线 - pythonx = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=…
对于DataFrame的每一行,在给定条件的情况下获取第一列的索引到新列中 - python这是我的数据框的一部分。data = [ ['1245', np.nan, np.nan, 1.0, 1.0, ''], ['1246', np.nan, 1.0, 1.0, 1.0, ''], ['1247', 1.0, 1.0, 1.0, 1.0, …
在Flask中测试文件上传 - python我在Flask集成测试中使用Flask-Testing。我有一个表单,该表单具有我要为其编写测试的徽标的文件上传,但是我不断收到错误消息:TypeError: 'str' does not support the buffer interface。我正在使用Python3。我找到的最接近的答案是this,但是它对我不起作用。这是我的许多尝…