繁体   English   中英

列表理解中的嵌套循环

[英]nested loop in list comprehension

我在l中有一个单词列表,如果l2中每个元组的第一个索引中存在任何单词,请删除整个元组。

我的代码:

l = ['hi', 'thanks', 'thank', 'bye', 'ok', 'yes', 'okay']
l2 = [('hi how are u', 'doing great'), ('looking for me', 'please hold')]
l3 = [k for k in l2 if not any(i in k[0] for i in l) ]

不知何故,该代码无法正常工作,我返回了l3的空列表。

我想要

l3 = [('looking for me', 'please hold')]

拆分k[0]以获得单词列表:

[k for k in l2 if not any(i in k[0].split() for i in l)]

这样,它检查i是否完全匹配一个单词。

也可以将其解释为k[0]并非以l任何一个开头,那么您可以这样做:

[k for k in l2 if not k[0].startswith(tuple(l))]

集使成员资格测试变得容易。 使用功能过滤列表。

import operator
first = operator.itemgetter(0

l = ['hi', 'thanks', 'thank', 'bye', 'ok', 'yes', 'okay']
l2 = [('hi how are u', 'doing great'), ('looking for me', 'please hold')]

def foo(t, l = set(l)):
    t = set(first(t).split())
    return bool(l & t)

l3 = [thing for thing in l2 if not foo(thing)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM