gpt4 book ai didi

python - 在 'if' 语句中设置多行条件的样式?

转载 作者:IT老高 更新时间:2023-10-28 12:00:53 25 4
gpt4 key购买 nike

有时我将 if 中的长条件分成几行。最明显的方法是:

  if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something

在视觉上不是很吸引人,因为 Action 与条件融为一体。但是,这是使用正确的 4 个空格的 Python 缩进的自然方式。

目前我正在使用:

  if (    cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something

但这不是很漂亮。 :-)

你能推荐一种替代方法吗?

最佳答案

您不需要在第二个条件行上使用 4 个空格。也许使用:

if (cond1 == 'val1' and cond2 == 'val2' and 
cond3 == 'val3' and cond4 == 'val4'):
do_something

另外,不要忘记空格比你想象的更灵活:

if (   
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something

不过,这两个都相当难看。

也许会丢失括号(Style Guide 不鼓励这样做)?

if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something

这至少给了你一些差异化。

甚至:

if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something

我想我更喜欢:

if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something

这里是 Style Guide ,(自 2010 年以来)建议使用括号。

关于python - 在 'if' 语句中设置多行条件的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/181530/

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