首页 > 解决方案 > Python - 创建一个检查列表列表中的新元素的函数

问题描述

我对如何创建一个检查列表中的子列表并检查这些子列表在整个列表本身中是否具有唯一元素的函数感到非常困惑。

alphabet_1 = [['a', 'b', 'c'], ['a', 'c', 'd'], ['a', 'e', 'f',], ['a', 'b', 'c']]

alphabet_2 = [['a', 'b', 'c'], ['a', 'b', 'c']

这些只是例子。

对于alphabet_1,由于第二个子列表在整个列表中至少有一个新元素,它转到下一个子列表,然后下一个失败,因为第四个子列表在整个列表中没有新元素,它停止。然后它计算它通过 aka 4 过去的子列表数量(直到停止)

对于alphabet_2,由于第二个子列表对整个列表有0 new,所以它停止了。这通过 2(直到停止)。

任何帮助将不胜感激!

标签: pythonpython-3.xlist

解决方案


def check_alphabet(a):
    i = 0
    curr_a = []
    for l in a:
        upd_a = list(set(curr_a + l))
        if len(upd_a) == len(curr_a):
            break
        i += 1
        curr_a = upd_a
    return i, curr_a

推荐阅读