【问题标题】:Return output after checking list1 is within list2检查 list1 在 list2 内后返回输出
【发布时间】:2019-07-23 07:45:22
【问题描述】:
list1 = [[['a','b'],['c','d']],[['f','g'],['h','i']],[['j','k','l'], ['a','b']]]
list2 = [['a','b'],['c','d'],['f','g'],['h','i']]

所以在 list1 中,有 3 个列表。我想检查 list1 中的列表是否是列表 2 的子集。但是列表列表中的所有列表都必须在 list2 中才能获得 True/Correct。如果所有内容都在 list2 中,则为 true,如果不是每个列表,则为 false。

[['a','b'],['c','d']]
[['f','g'],['h','i']]
[['j','k','l'], ['a','b']]

所以条件如下

These are from list1, and we're checking against list2

Both [a, b] and [c, d] should be in list 2 -> Both are in list 2, so Return True
Both [f, g] and [h, i] should be in list 1 -> Both are in list 2, so return true
Both [j, k, l] and [a, b] should be in list 1 -> f, k, l is not in list 2, so return False even though a, b are in list 2

Here is my desired output for above results

[True, True, False] 

val1 = True
val2 = True
val3 = False

代码

def xlist(list1, list2):
    if all(letter in list1 for letter in list2):
        print('True')

print xlist(list1, list2)

final = []
"""I am checking i in list1. In actual, I should be checking all lists within the list of list1."""
    for i in list1:
        print(xlist(list1, list2))
        final.append(xlist(list1, list2))
        print(final)

【问题讨论】:

  • 虽然很明显,但您并没有说明实际出了什么问题。如果您遇到错误,您应该附上它。如果您的输出错误,您应该向我们展示实际输出与预期输出的对比(您实际上是这样做的,只是缺少实际输出)

标签: python


【解决方案1】:

您的问题是您没有从 xlist 函数返回任何值(printreturn 不同)。将其更改为:

def xlist(list1, list2):
    return all(letter in list1 for letter in list2)

然后:

final = []
for i in list1:
    final.append(xlist(list2, i))
print(final)

结果是:

[True, True, False]

作为一种替代的、更短的方法,您可以将all 函数与嵌套的list comprehension 一起使用:

>>> list1 = [[['a','b'],['c','d']],[['f','g'],['h','i']],[['j','k','l'], ['a','b']]]
>>> list2 = [['a','b'],['c','d'],['f','g'],['h','i']]
>>> [all(item in list2 for item in sublist) for sublist in list1]
[True, True, False]

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多