更多pythonic方式来查看列表列表

时间:2016-05-13 17:52:17

标签: python python-3.x

我有两份清单。我是在迭代它们并在相同位置寻找共同元素。

如果列表中有任何元素 elements_to_check列表匹配并且不在unique_list中我将其添加到那里。

如果没有元素匹配,我想将此列表附加到not_match_list。

下面是我的代码示例。它几乎可以工作。我不知道为什么最后在not_match_list中我有[2,3,'d'](例如[2,3,'c']或[2,4'd']已经在unique_list中) 任何人都可以解释一下为什么not_match_list中有[2,3,'d']和/或建议我如何重写这个代码更加pythonic,拜托?

unique_list = [[1, 2, 'a'], [4, 2, 'b'], [1, 3, 'c'], [2, 3, 'c'], [2, 4, 'd']]
not_match_list = []
elements_to_check = [[2, 3, 'a'], [3, 4, 'a'], [4, 2, 'a'], [4, 2, 'a'], [2, 3, 'd'], [9, 9, 'z']]

print(unique_list)
for unique_element in unique_list:
    for element_to_check in elements_to_check:
        if element_to_check[0] == unique_element[0] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check[1] == unique_element[1] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check[2] == unique_element[2] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check not in unique_list and element_to_check not in not_match_list:
            not_match_list.append(element_to_check)

print(unique_list)
print(not_match_list)

预期结果:

unique_list =  [[1, 2, 'a'], [4, 2, 'b'], [1, 3, 'c'], [2, 3, 'c'], [2, 4, 'd'], [2, 3, 'a'], [3, 4, 'a'], [4, 2, 'a'], [2, 3, 'd']]
not_match_list =  [[9, 9, 'z']]

2 个答案:

答案 0 :(得分:0)

这不是一个完整的解决方案,但如果我理解正确,你至少可以简化这个:

if element_to_check[0] == unique_element[0] and element_to_check not in unique_list:
    unique_list.append(element_to_check)
elif element_to_check[1] == unique_element[1] and element_to_check not in unique_list:
    unique_list.append(element_to_check)
elif element_to_check[2] == unique_element[2] and element_to_check not in unique_list:
    unique_list.append(element_to_check)
elif element_to_check not in unique_list and element_to_check not in not_match_list:
    not_match_list.append(element_to_check)

到此:

if any(to_check == unique for to_check, unique in zip(element_to_check, unique_list)) and element_to_check not in unique_list:
    unique_list.append(element_to_check)
else:
    not_match_list.append(element_to_check)

答案 1 :(得分:0)

我相信只需稍微重新安排代码,您就可以实现您想要的目标:

for element_to_check in elements_to_check:
    for unique_element in unique_list:
        if element_to_check[0] == unique_element[0] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check[1] == unique_element[1] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check[2] == unique_element[2] and element_to_check not in unique_list:
            unique_list.append(element_to_check)

    if element_to_check not in unique_list and element_to_check not in not_match_list:
        not_match_list.append(element_to_check)