比较平面列表和嵌套列表

时间:2014-07-07 17:03:22

标签: python python-2.7

我想比较下面的两个列表。 edges是元组列表,而b_edge是元组的嵌套列表。我想要的是追加edges[i][2] to all b_edge[i][j] if b_edge[i][j] == edge[0:2].

以下是清单:

edges = [('1.0', '2.0',{'length':0.35}),('2.0', '3.0',{'length':0.46,}),('3.0', '4.0', {'length':0.49}),(4.0, 5.0,{'length':0.22}),('5.0', '6.0',{'length':0.54}),('6.0', '7.0', {'length':0.49}),('7.0', '8.0',{'length':0.22}),(5.0, 6.0,{'length':0.54})]

b_edge = [[('1.0', '2.0'), ('2.0', '3.0'), ('3.0', '4.0')], [('5.0', '6.0'), ('6.0', '7.0'), ('7.0', '8.0')]]

期望的输出:

[[('1.0', '2.0', {'length': 0.35}), ('2.0', '3.0', {'length': 0.46}), ('3.0', '4.0', {'length': 0.49})], [('5.0', '6.0', {'length': 0.35}), ('6.0', '7.0', {'length': 0.46}), ('7.0', '8.0', {'length': 0.49})]

我试过了:

result = []
for j in b_edge:
    temp = []
    for l,k in enumerate(j):
        if j[l][0:2] == edges[l][:2]:
            temp.append(k + (edges[l][2],))
    result.append(temp)
print 'result', result

并且还在SO compare two lists and print out unequal elements和类似问题上检查了这些答案,但它们与我想要的完全不符。

得到了这个结果:

[[('1.0', '2.0', {'length': 0.35}), ('2.0', '3.0', {'length': 0.46}), ('3.0', '4.0', {'length': 0.49})], []]

似乎只将字典附加到嵌套列表中的第一个元素,而第二个元素只输出一个空列表。

谢谢。

3 个答案:

答案 0 :(得分:2)

一个荣耀的衬垫:

result = [[edge for edge in edges if (edge[0], edge[1]) in edge_group] for edge_group in b_edge]

现在,我的嘴里的边缘感觉很奇怪。

另外,我知道你说的数据就是你如何得到的,但我个人仍然会把它改成像这样的字典:

edge_lengths = {(edge[0], edge[1]): edge[2]['length'] for edge in edges}
# Gives you:
# {('1.0', '2.0'): 0.35, ('3.0', '4.0'): 0.49, ... , ('5.0', '6.0'): 0.54}

# Get lengths
print [[edge_lengths[edge] for edge in edge_group] for edge_group in b_edge]
# [[0.35, 0.46, 0.49], [0.54, 0.49, 0.22]]

当然取决于你:)

答案 1 :(得分:2)

试试这个:

result = b_edge
tmp_dict = { (i[0],i[1]): i[2] for i in edges }
for index_j, j in enumerate(b_edge):
    for index_i, i in enumerate(j):
        if i in tmp_dict:
            result[index_j][index_i] = result[index_j][index_i] + (tmp_dict[i],)

我创建了一个字典,用于将您的元组映射到您的{“length”}字典,并用它来产生您想要的输出。

答案 2 :(得分:1)

我会创建一个数字元组的映射到这样的长度:

>>> num_to_len = {x[0:2]:x[2] for x in edges}
>>> num_to_len
{(4.0, 5.0): {'length': 0.22}, ('3.0', '4.0'): {'length': 0.49}, (5.0, 6.0): {'length': 0.54}, ('1.0', '2.0'): {'length': 0.35}, ('6.0', '7.0'): {'length': 0.49}, ('2.0', '3.0'): {'length': 0.46}, ('7.0', '8.0'): {'length': 0.22}, ('5.0', '6.0'): {'length': 0.54}}

然后像这样建立你想要的结果:

>>> [[x if x not in num_to_len else x+(num_to_len[x],) for x in b_edge[0]]]
[[('1.0', '2.0', {'length': 0.35}), ('2.0', '3.0', {'length': 0.46}), ('3.0', '4.0', {'length': 0.49})]]

请注意,如您指定的那样将所有内容包装在另一个列表中可能不是必需的。因此,除非您有充分的理由,否则请跳过列表解析中最外面的括号。