将For循环转换为List Comprehension:测试列表2中的元素是否与列表1中的元素部分匹配 [英] Convert For Loop to List Comprehension: Testing if elements in list 2 are partial match for elements in list 1

查看:140
本文介绍了将For循环转换为List Comprehension:测试列表2中的元素是否与列表1中的元素部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些python /编程新手在这里,

我已经想出了一个2嵌套for循环代码来测试第二循环的元素是第一个列表中元素的部分(或完整)匹配,如果是的话,这些元素将从第一个列表中删除。这里是代码:

 >>> lst = [我的名字是Bob Jenkins,Tommy Cooper I am,I be Bazil,I Tarzan] 
>>> names = [Bob,Tarzan]
>>> for lst lst:
for n in name:
if n in l:
lst.remove(l)


>>> ; print lst
['Tommy Cooper I','I be Bazil']

这里的问题是,我并不想要修改 lst ,但创建一个新的列表。因此,列表理解提高了头。但是,我还没有弄清楚列表理解是否能解决这个问题。我已经尝试了 [我为我在lst中如果n不在我名字中n] 但是这不起作用。当然, .remove 方法不适用于列表理解。过去一个小时我一直困惑,却不能拿出任何东西。

有什么想法?

解决方案

/ p>

  lst = [我的名字是Bob Jenkins,Tommy Cooper I am,我是Bazil,I Tarzan ] 
names = [Bob,Tarzan]

new = [a如果全部(x不在x中名称中)]
打印新


somewhat of a python/programming newbie here,

I have come up with a code of 2 nested for loops to test if the elements of the the 2nd loop are a partial (or complete) match of the elements in the first list, and if so those elements are removed from the 1st list. Here is the code:

>>> lst = ["my name is Bob Jenkins", "Tommy Cooper I am", "I be Bazil", "I Tarzan"]
>>> names = ["Bob", "Tarzan"]
>>> for l in lst:
        for n in names:
            if n in l:
                lst.remove(l)


>>> print lst
['Tommy Cooper I am', 'I be Bazil']

The problem here is that I don't actual want to modify lst, but create a new list. Thus list comprehension raises its head. However, I have not been able to figure out a list comprehension to pull this off. I have tried [i for i in lst for n in names if n not in i] but this does not work. Of course the .remove method is not for list comprehension. I have been puzzling for the past hour, but cannot come up with anything.

Any ideas?

解决方案

There you go :) :

lst = ["my name is Bob Jenkins", "Tommy Cooper I am", "I be Bazil", "I Tarzan"]
names = ["Bob", "Tarzan"]

new=[a for a in lst if all(x not in a for x in names) ]
print new

这篇关于将For循环转换为List Comprehension:测试列表2中的元素是否与列表1中的元素部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆