首页 > 解决方案 > 将字典转换为元组列表

问题描述

我是 Python 的初学者,我正在尝试解决中文邮递员问题并遵循本教程

我在一步:计算最小重量匹配。我需要将字典转换为元组列表

下面的代码是我到目前为止所拥有的

# Compute min weight matching.
# Note: max_weight_matching uses the 'weight' attribute by default as the attribute to maximize.
odd_matching_dupes = nx.algorithms.max_weight_matching(g_odd_complete, True)

print('Number of edges in matching: {}'.format(len(odd_matching_dupes)))

# Preview of matching with dupes
odd_matching_dupes

# Convert matching to list of deduped tuples
odd_matching = list(pd.unique([tuple(sorted([k, v])) for k, v in 
odd_matching_dupes.items()]))

我得到的输出odd_matching_dupes是:

{('rep1', 'rep2'),
('rep12', 'rep16'),
('rep17', 'rep13'),
('rep27', 'rep19'),
('rep7', 'rep10'),
('rep8', 'rep5')}

这是我收到的错误消息:

  ---------------------------------------------------------------------------
  AttributeError                            Traceback (most recent call last)
<ipython-input-84-7da9b4bbe8a5> in <module>
142 
143 # Convert matching to list of deduped tuples
--> 144 odd_matching = list(pd.unique([tuple(sorted([k, v])) for k, v in 
odd_matching_dupes.items()]))

AttributeError: 'set' object has no attribute 'items'

标签: pythonpandascsvattributeerror

解决方案


推荐阅读