擅长:python、mysql、java
<p>这也可以很好地与发电机。在</p>
<p>如果不必压缩键项对,则此生成器将生成键项对;如果已压缩,则将项保存到最后一个项,然后生成它,并将新键与保存的项联接起来。在</p>
<p>有了这个生成器,就可以构造一个新的有序dict。在</p>
<pre><code>from collections import OrderedDict
def sqaushDict(d, ind, new_key):
""" Takes an OrderedDictionary d, and yields its key item pairs,
except the ones at an index in indices (ind), these items are merged
and yielded at the last position of indices (ind) with a new key (new_key)
"""
if not all(x < len(d) for x in ind):
raise IndexError ("Index out of bounds")
vals = []
for n, (k, i), in enumerate(d.items()):
if n in ind:
vals += [i]
if n == ind[-1]:
yield (new_key, " ".join(vals))
else:
yield (i, k)
d = OrderedDict([
("Sample Code", "Vendor Sample ID"),
("Donor ID", "Vendor Subject ID"),
("Format", "Material Format"),
("Sample Type", "Sample Type"),
("Age", "Age"),
("Gender", "Gender"),
])
t = OrderedDict(squashDict(d, [2, 3], "Random"))
print(t)
</code></pre>