<p>您可以通过对索引进行降序排序来优化这一点,然后可以使用<code>dict.pop(key,None)</code>立即检索并删除键/值,但我决定不这样做,按照<code>indices</code>中出现的顺序追加值。在</p>
<pre><code>from collections import OrderedDict
from pprint import pprint
def mergeEm(d,indices,key):
"""Merges the values at index given by 'indices' on OrderedDict d into a list.
Appends this list with key as key to the dict. Deletes keys used to build list."""
if not all(x < len(d) for x in indices):
raise IndexError ("Index out of bounds")
vals = [] # stores the values to be removed in order
allkeys = list(d.keys())
for i in indices:
vals.append(d[allkeys[i]]) # append to temporary list
d[key] = vals # add to dict, use ''.join(vals) to combine str
for i in indices: # remove all indices keys
d.pop(allkeys[i],None)
pprint(d)
fields= OrderedDict([
("Sample Code", "Vendor Sample ID"),
("Donor ID", "Vendor Subject ID"),
("Format", "Material Format"),
("Sample Type", "Sample Type"),
("Age", "Age"),
("Gender", "Gender"),
("Ethnicity/ Race", "Race"),
("Sample Type", "Sample Type"),
("Organ", "Organ"),
("Pathological Diagnosis", "Diagnosis"),
("Detailed Pathological Diagnosis", "Detailed Diagnosis"),
("Clinical Diagnosis/Cause of Death", "Detailed Diagnosis option 2"),
("Dissection", "Dissection"),
("Quantity (g, ml, or ug)", "Quantity"),
("HIV", "HIV"),
("HEP B", "HEP B")
])
pprint(fields)
mergeEm(fields, [5,4,2], "tata")
</code></pre>
<p>输出:</p>
^{pr2}$