我在 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))]
关于python - 列表理解中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40445937/