gpt4 book ai didi

Python 从字符串列表中删除字符串列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:52 24 4
gpt4 key购买 nike

我正在尝试从 URL 列表中删除几个字符串。我有超过 30 万个 URL,我正试图找出哪些是原始 URL 的变体。这是我一直在使用的玩具示例。

URLs = ['example.com/page.html',
'www.example.com/in/page.html',
'example.com/ca/fr/page.html',
'm.example.com/de/page.html',
'example.com/fr/page.html']

locs = ['/in', '/ca', '/de', '/fr', 'm.', 'www.']

我最后想要的是没有语言或位置的页面列表:

desired_output = ['example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html']

我已经尝试了列表理解和嵌套 for 循环,但没有任何效果。谁能帮忙?

# doesn't remove anything
for item in URLs:
for string in locs:
re.sub(string, '', item)

# doesn't remove anything
for item in URLs:
for string in locs:
item.strip(string)

# only removes the last string in locs
clean = []
for item in URLs:
for string in locs:
new = item.replace(string, '')
clean.append(new)

最佳答案

你必须再次将replace的结果赋值给item:

clean = []
for item in URLs:
for loc in locs:
item = item.replace(loc, '')
clean.append(item)

或者简而言之:

clean = [
reduce(lambda item,loc: item.replace(loc,''), [item]+locs)
for item in URLs
]

关于Python 从字符串列表中删除字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39257990/

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