itertools组合创建一个缺失的对

时间:2016-08-06 16:35:28

标签: list python-2.7 hash combinations itertools

我使用以下代码从数组列表创建了一个组合哈希:

all_waypoints = [item1,item2,...]
waypoint_distances = {}
 for (waypoint1, waypoint2) in combinations(all_waypoints, 2):
 waypoint_distances[frozenset([waypoint1, waypoint2])] = distance 

此后,我使用以下代码浏览创建的组合列表:

for (waypoint1, waypoint2) in waypoint_distances.keys():

问题在于程序暂停代码的一半,并指出:

ValueError: need more than 1 value to unpack

调试程序后,我发现当程序的其余部分停止时,waypoint_distances哈希包含以下元素:

...,frozenset(['an-item', 'another-item']), frozenset(['an-item']),...

我唯一能想到的是列表是组合列表是用itertool创建的,我怎么能绕过这个?在7050组合哈希周围发现问题,组合总量约为16k。

提前致谢

1 个答案:

答案 0 :(得分:1)

如果您的项目列表中有一些重复项,则可能会发生这种情况:

from itertools import combinations

all_waypoints = [1,2,3,1]
waypoint_distances = {}
for (waypoint1, waypoint2) in combinations(all_waypoints, 2):
    print(set([waypoint1, waypoint2]))

结果:

{1, 2}
{1, 3}
{1}
{2, 3}
{1, 2}
{1, 3}

你必须消除sets长度= 1

for (waypoint1, waypoint2) in combinations(all_waypoints, 2):
  fs = frozenset([waypoint1, waypoint2])
  if len(fs)==2:
     waypoint_distances[fs] = distance 

或更好:使用set

消除来源的重复项
for (waypoint1, waypoint2) in combinations(set(all_waypoints), 2):