gpt4 book ai didi

python - 从包含某些关键字的列表中删除多个字符串元素

转载 作者:行者123 更新时间:2023-12-05 09:08:21 25 4
gpt4 key购买 nike

我有一个名为文件的列表,由字符串元素组成:

files = ['Upside Your Head.txt', 'The Mighty Quinn - [Remastered].txt', 'The Mighty Quinn - (live).txt', 'Fixin To Die (Mono version).txt', '10,000 Men - [Remastered].txt', '10,000 Men.txt', '10.000 Men - (live).txt']

我正在尝试删除包含特定关键字的元素(例如 Live、Remastered、Mono)。我写的代码是这样的:

files = [i for i in files if '(Live)' not in i]
files = [i for i in files if '[Remastered]' not in i]
files = [i for i in files if '(Mono' not in i]

将上述所有三行都包含在一个语句中的更好做法是什么?考虑到我想稍后添加更多关键字。

最佳答案

概括这一点的第一步是将多个条件与逻辑运算符结合起来:

files = [i for i in files if '(Live)' not in i]
files = [i for i in files if '[Remastered]' not in i]
files = [i for i in files if '(Mono' not in i]

成为

files = [
i for i in files
if (
'(Live)' not in i
and '[Remastered]' not in i
and '(Mono' not in i
)
]

或者,通过 De Morgan's laws ,

files = [
i for i in files
if not (
'(Live)' in i
or '[Remastered]' in i
or '(Mono' in i
)
]

现在,为了能够从预定义列表中获取关键字并相应地自动调整条件数量,我们可以使用内置的 allany功能:

  • a and b and c可以替换为all([a, b, c])
  • a or b or c 可以替换为 any([a, b, c])

(参见:How to apply a logical operator to all elements in a python list)

除了列表,我们还可以将生成器表达式传递给allany

因此,条件

if (
'(Live)' not in i
and '[Remastered]' not in i
and '(Mono' not in i
)

可以写成

if all(keyword not in i for keyword in ['(Live)', '[Remastered]', '(Mono'])

if not (
'(Live)' in i
or '[Remastered]' in i
or '(Mono' in i
)

作为

if not any(keyword in i for keyword in ['(Live)', '[Remastered]', '(Mono'])

结果,代码可以变成

keywords = ['(Live)', '[Remastered]', '(Mono']
files = [i for i in files if all(keyword not in i for keyword in keywords)]

keywords = ['(Live)', '[Remastered]', '(Mono']
files = [i for i in files if not any(keyword in i for keyword in keywords)]

关于python - 从包含某些关键字的列表中删除多个字符串元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63614302/

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