簡體   English   中英

將列表b中的任何字符串與列表a匹配。 一個很長的句子

[英]match any of string in list b with list a. a is a long sentences

a = ['http://www.yahoo.com', 'http://www.google.net', 'gorilla', 'house.com', 'i love the net very much']
b = ['com', 'http', 'net']

result = ['http://www.yahoo.com', 'http://www.google.net', 'house.com', 'i love the net very much']

我如何在a中找到b? 匹配a中的b。 一個很長的句子

我的正則表達式

for element in a:
    m = re.match("anything match in b right?")
    if m:
        print (m.group())

我不太確定在re.match中放什么

a = ['http://www.yahoo.com', 'http://www.google.net', 'gorilla', 'house.com', 'i love the net very much']
b = ['com', 'http', 'net']
print list(set([i for i in a for j in b if j in i]))

編輯:

對於a中的所有b:

a = ['http://www.yahoo.com', 'http://www.google.net', 'gorilla', 'house.com', 'i love the net very much http and com too']
b = ['com', 'http', 'net']

print set(a)-set([i for i in a for j in b if j not in i])

不是正則表達式解決方案,但我認為您可以遍歷每個字符串,並且可以使用any()進行檢查。 范例-

result = []
for i in a:
    if any(x in i for x in b):
        result.append(i)

示例/演示-

>>> a = ['http://www.yahoo.com', 'http://www.google.net', 'gorilla', 'house.com', 'i love the net very much']
>>> b = ['com', 'http', 'net']
>>>
>>> result = []
>>> for i in a:
...     if any(x in i for x in b):
...         result.append(i)
...
>>> result
['http://www.yahoo.com', 'http://www.google.net', 'house.com', 'i love the net very much']

列表理解解決方案-

result = [i for i in a if any(x in i for x in b)]

示例/演示-

>>> a = ['http://www.yahoo.com', 'http://www.google.net', 'gorilla', 'house.com', 'i love the net very much']
>>> b = ['com', 'http', 'net']
>>> result = [i for i in a if any(x in i for x in b)]
>>>
>>> result
['http://www.yahoo.com', 'http://www.google.net', 'house.com', 'i love the net very much']

使用嵌套循環,使用b中的每一個通過find()函數檢查a中的每一個。

if b[x].find(a[y]) != -1:

該if語句將指示是否在b [x]中找到a [y]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM