gpt4 book ai didi

python - 从另外两个列表派生新的列表列表,如果 L1 中的元素不在 L2 中,则附加这些元素

转载 作者:行者123 更新时间:2023-11-30 22:02:38 25 4
gpt4 key购买 nike

所以我一直在为即将到来的测试而学习,在练习时我发现了这个脚本;它应该返回一个新的列表列表,其中包含来自 L1 的列表,但不包含来自 L2 的任何字符串:

我所做的是将 L2 中的每个元素与 L1 中的元素进行比较,并将它们添加到 listas 中,没有任何重复项。我陷入困境的部分是在我的循环完成运行之后,我得到了一个列表列表,但没有任何实际的比较。我尝试使用第二个列表,它可以工作,但如果 len(L2) > 2 则不起作用,也 .remove() 但有时该元素删除尚未在列表中,我收到一些错误。

from typing import List
def non_intersecting(L1: List[List[str]], L2: List[str]) -> List[List[str]]:
"""Return a new list that contains the original lists inside L1 that do not
contain any of the string in L2

>>> non_intersecting([['e', 'h', 'c', 'w'], ['p', 'j'], ['w', 's', 'u']], ['k', 'w'])
[['p', 'j']]
"""

listas = []

if len(L2) == 0:
return L1
elif len(L2) > 0:
for index in range(len(L2)):
for lists in L1:
if lists not in listas:
if L2[index] not in lists:
listas.append(lists)

return listas

有什么帮助吗?如果没有任何模块或 ziplambdas 就可以做到这一点,那就太好了,因为我不想提交这个,而是在测试之前了解基础知识。

最佳答案

def non_intersecting(l1, l2):
out = []
for sub_list in l1:
if len(list(set(sub_list).intersection(l2))) == 0: #no common strings
out.append(sub_list)
return out

对于这个简单的操作,不需要添加 List() 构造函数..

关于python - 从另外两个列表派生新的列表列表,如果 L1 中的元素不在 L2 中,则附加这些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53752223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com