小编Rab*_*dra的帖子

字符串替换可以用列表理解来写吗?

我有一个文本和一个列表。

text = "Some texts [remove me] that I want to [and remove me] replace"
remove_list = ["[remove me]", "[and remove me]"]
Run Code Online (Sandbox Code Playgroud)

我想替换字符串中列表中的所有元素。所以,我可以这样做:

for element in remove_list:
    text = text.replace(element, '')
Run Code Online (Sandbox Code Playgroud)

我还可以使用正则表达式。但这可以在列表理解或任何单行中完成吗?

python list-comprehension python-3.x

2
推荐指数
1
解决办法
545
查看次数

如何在python中的一行if条件中编写多个for循环?(特定于 DOCX)

我有以下代码。

for row in table.rows:
    for cell in row.cells:
        if cell.tables:
            <some code>
        else:
            <different code>
Run Code Online (Sandbox Code Playgroud)

但我需要将其写在一行中,如下所示,以便 in<different code>else运行一次,而不是由于循环而多次运行。

if any(cell.tables for cell in row.cells for row in table.rows):
    <some code>
else:
    <different code>
Run Code Online (Sandbox Code Playgroud)

然而,这一行在row.cells处显示未解决的引用“行”错误。这个衬垫可以工作,但不知道为什么它在这个 docx 表案例中不起作用。如果除了单行 if 条件之外,是否可以以不同且更好的方式完成此操作,我也欢迎提出建议。

python python-3.x python-docx

1
推荐指数
1
解决办法
7133
查看次数