【问题标题】:Python List Filtering Removes Too ManyPython 列表过滤删除太多
【发布时间】:2021-05-06 02:00:38
【问题描述】:

我将 python 的 url 列表作为字符串。我正在尝试删除所有包含两个正斜杠的字符串 (//)。以下是我尝试的方法:

filtered_list = [x for x in original_list if 'https://www.ourlads.com/ncaa-football-depth-charts/player//' not in x]

但是,当我运行它时,它会删除所有带有 // 的字符串以及甚至不包括 // 的其他字符串。

这是原始列​​表的示例:

original_list = ['https://www.ourlads.com/ncaa-football-depth-charts/player/devonta-smith/123433',
'https://www.ourlads.com/ncaa-football-depth-charts/player//0',
'https://www.ourlads.com/ncaa-football-depth-charts/player//116922',
'https://www.ourlads.com/ncaa-football-depth-charts/player/alex-leatherwood/123411']

我可以改变什么,让它只删除带有 // 的字符串?

【问题讨论】:

  • 你能复制那些应该被删除而没有被删除的字符串吗?测试您的代码时似乎一切正常。
  • 嗨@CarlKristensen 我编辑了问题以包含列表示例

标签: python-3.x list filtering


【解决方案1】:

您的代码似乎正在运行。 但另一种方法是通过正则表达式。

import re

original_list = ['https://www.ourlads.com/ncaa-football-depth-charts/player/devonta-smith/123433',
'https://www.ourlads.com/ncaa-football-depth-charts/player//0',
'https://www.ourlads.com/ncaa-football-depth-charts/player//116922',
'https://www.ourlads.com/ncaa-football-depth-charts/player/alex-leatherwood/123411']

filtered_list = [x for x in original_list if not re.match(r"^https://.*//", x)]
filtered_list

过滤器列表:

['https://www.ourlads.com/ncaa-football-depth-charts/player/devonta-smith/123433',
 'https://www.ourlads.com/ncaa-football-depth-charts/player/alex-leatherwood/123411']

【讨论】:

  • 谢谢!不知道为什么它不能在我的机器上工作,但正则表达式版本工作!
猜你喜欢
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2019-02-17
  • 2014-06-29
相关资源
最近更新 更多