python - 在其他列表中迭代 python 列表

标签 python

我在两个列表之间进行迭代以查看其中一个列表是否包含另一个列表的元素时遇到问题。在其中一个列表中,我还有另一个列表。有时这个列表只有字符串,有时是字符串和..另一个列表。

所以问题就在这里。如果它只有字符串,我想知道这些字符串的 ALL 是否都在 Mainlist 内。

但是,如果我有 srtings AND 另一个列表..我想知道列表之外的ALL 字符串是否都在 Mainlist 并且如果列表中的AT LEAST ONE 字符串位于Mainlist 中。


所以,假设我有一个主列表: 主列表 = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF']

现在,我有其他列表想要迭代此 Mainlist:

list1 = [['AA', ['BB', 'YY']], ['AA', 'GG']]

list1 上,我有两个列表:['AA', ['BB', 'YY']]['AA', 'GG '] 一个只有字符串,另一个有字符串和另一个列表。

现在我需要知道 list1 上的元素是否在 Mainlist 上,并获取 list1 中给我的元素的索引正确结果。

在这种情况下,在索引 0 处它会是True。因为 Mainlist 包含项目 'AA''BB'


其他示例:

list2 = [['AA', 'JJ'], ['EE', 'FF']] # False at index 0 = Mainlist does not have 'JJ' / True at index 1 = Mainlist has 'EE' and 'FF'
list3 = [['AA', 'KK', ['BB', 'CC']], ['JJ', 'GG']] # False at index 0 item 'KK' is not in Mainlist / False at index 1 = Mainlist does not have 'JJ' and 'GG'
list4 = [['EE', 'FF', "OO"], ['AA', 'BB', 'CC',['DD', 'MM']], ['GG', ['BB', 'CC', 'DD']]] #False at index 0 = Mainlist does not have 'OO' / True at index 1  = Even if 'MM' is not in Mainlist, 'DD' is. / False  at index 2 = 'GG' is not in Mainlist

我在尝试实现这一目标时感到头疼..有没有人有提示可以帮助我解决这个问题? 提前致谢

最佳答案

你可以尝试这个,返回一个包含每个索引及其各自 bool 值的字典:

list2 = [['AA', 'JJ'], ['EE', 'FF']] # False at index 0 = Mainlist does not have 'JJ' / True at index 1 = Mainlist has 'EE' and 'FF'
list3 = [['AA', 'KK', ['BB', 'CC']], ['JJ', 'GG']] # False at index 0 item 'KK' is not in Mainlist / False at index 1 = Mainlist does not have 'JJ' and 'GG'
list4 = [['EE', 'FF', "OO"], ['AA', 'BB', 'CC',['DD', 'MM']], ['GG', ['BB', 'CC', 'DD']]] #False at index 0 = Mainlist 
Mainlist = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF']


def func(ls):
    dct={}
    for idx,l in enumerate(ls):
        if all(isinstance(elem, str) for elem in l):
            dct.update({idx:all(elem in Mainlist for elem in l)})
        else:
            cond=all(el in Mainlist for el in [i for i in l if isinstance(i, str)]) and any(ele in Mainlist for el in [i for i in l if isinstance(i, list)] for ele in el)
            dct.update({idx:cond})
    return dct

print(func(list2))
print(func(list3))
print(func(list4))

输出:

{0: False, 1: True}
{0: False, 1: False}
{0: False, 1: True, 2: False}

关于python - 在其他列表中迭代 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62583217/

相关文章:

python - 在中国运行应用引擎应用程序?

Python通过字符串名称导入子模块?

python - Numpy:作为 Matlab 的赋值和索引

python - 如何使用基于类的 View 从不同的应用程序渲染 django 中的模板?

python - 如何编写 setup.py 来安装 SWIG 构建的 python 扩展(xxx.so 文件)?

python - 提取并重命名 zip 文件夹

python - 四舍五入到 10

python - 使用 Flask-Migrate 在多个分支上工作

python - 将函数应用/映射到前一行

python - 当 python 脚本遇到错误或停止时如何通知自己?