Eli*_*sky 618 python if-statement coding-style
有时我会将ifs中的长条件分成几行.最明显的方法是:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Run Code Online (Sandbox Code Playgroud)
视觉上不是很吸引人,因为动作与条件相融合.但是,这是使用4个空格的正确Python缩进的自然方式.
目前我正在使用:
if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Run Code Online (Sandbox Code Playgroud)
但这不是很漂亮.:-)
你能推荐另一种方式吗?
Har*_*mbe 679
您不需要在第二个条件行上使用4个空格.也许用:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Run Code Online (Sandbox Code Playgroud)
另外,不要忘记空格比您想象的更灵活:
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
Run Code Online (Sandbox Code Playgroud)
但这两个都相当难看.
也许会丢失括号(虽然风格指南不鼓励这样)?
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
Run Code Online (Sandbox Code Playgroud)
这至少给你一些区别.
甚至:
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
Run Code Online (Sandbox Code Playgroud)
我想我更喜欢:
if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
Run Code Online (Sandbox Code Playgroud)
这是样式指南,(自2010年起)建议使用括号.
S.L*_*ott 116
我在退化的情况下使用了以下内容,它只是简单的AND或OR.
if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):
if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):
Run Code Online (Sandbox Code Playgroud)
它削减了一些角色,并清楚地表明这种情况没有微妙之处.
Kev*_*tle 54
有人必须在这里支持使用垂直空白!:)
if ( cond1 == val1
and cond2 == val2
and cond3 == val3
):
do_stuff()
Run Code Online (Sandbox Code Playgroud)
这使得每个条件都清晰可见.它还可以更清晰地表达更复杂的条件:
if ( cond1 == val1
or
( cond2_1 == val2_1
and cond2_2 >= val2_2
and cond2_3 != bad2_3
)
):
do_more_stuff()
Run Code Online (Sandbox Code Playgroud)
是的,为了清晰起见,我们正在对一些垂直房地产进行折衷.非常值得IMO.
Dee*_*tan 24
当我有一个非常大的if条件时,我更喜欢这种风格:
if (
expr1
and (expr2 or expr3)
and hasattr(thingy1, '__eq__')
or status=="HappyTimes"
):
do_stuff()
else:
do_other_stuff()
Run Code Online (Sandbox Code Playgroud)
kra*_*oti 24
这是我个人的看法:长期条件(在我看来)是一种代码气味,暗示重构为布尔返回的函数/方法.例如:
def is_action__required(...):
return (cond1 == 'val1' and cond2 == 'val2'
and cond3 == 'val3' and cond4 == 'val4')
Run Code Online (Sandbox Code Playgroud)
现在,如果我找到一种方法使多线条件看起来很好,我可能会发现自己满足于拥有它们并跳过重构.
另一方面,让他们扰乱我的审美意识就是对重构的一种激励.
因此,我的结论是,多线条件应该看起来很丑陋,这是避免它们的动机.
Fed*_*oni 23
这并没有改善太多,但......
allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4')
if allCondsAreOK:
do_something
Run Code Online (Sandbox Code Playgroud)
Dzi*_*inX 19
我建议将and关键字移动到第二行,并将包含条件的所有行缩进两个空格而不是四个:
if (cond1 == 'val1' and cond2 == 'val2'
and cond3 == 'val3' and cond4 == 'val4'):
do_something
Run Code Online (Sandbox Code Playgroud)
这正是我在代码中解决这个问题的方法.将关键字作为行中的第一个单词使条件更具可读性,减少空格数可进一步区分条件和操作.
Mar*_*ery 10
似乎值得引用PEP 0008(Python的官方风格指南),因为它以适度的长度评论这个问题:
当
if-statement 的条件部分足够长以要求它跨多行写入时,值得注意的是两个字符关键字(即if)的组合,加上一个空格,加上一个左括号创建一个自然的4-多行条件的后续行的空格缩进.这可能会与嵌套在if-statement中的缩进代码集产生视觉冲突,该代码集自然也会缩进到4个空格.该PEP没有明确地说明如何(或是否)进一步在视觉上区分这些条件线与if-statement 内的嵌套套件.在这种情况下可接受的选择包括但不限于:Run Code Online (Sandbox Code Playgroud)# No extra indentation. if (this_is_one_thing and that_is_another_thing): do_something() # Add a comment, which will provide some distinction in editors # supporting syntax highlighting. if (this_is_one_thing and that_is_another_thing): # Since both conditions are true, we can frobnicate. do_something() # Add some extra indentation on the conditional continuation line. if (this_is_one_thing and that_is_another_thing): do_something()
注意上面引用中的"不限于"; 除了风格指南中提出的方法之外,在这个问题的其他答案中提出的一些方法也是可以接受的.
这就是我所做的,记住"所有"和"任何"接受一个可迭代的,所以我只是在列表中放入一个长条件并让"all"完成工作.
condition = [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4']
if all(condition):
do_something
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我喜欢为长 if 语句添加含义。我必须搜索代码才能找到合适的示例,但这是我想到的第一个示例:假设我碰巧遇到了一些奇怪的逻辑,我想根据许多变量显示某个页面。
中文: “如果登录的用户不是管理员教师,而只是普通教师,并且本身不是学生……”
if not user.isAdmin() and user.isTeacher() and not user.isStudent():
doSomething()
Run Code Online (Sandbox Code Playgroud)
当然,这看起来不错,但是阅读这些 if 语句是一项繁重的工作。我们将逻辑分配给有意义的标签怎么样?“标签”实际上是变量名:
displayTeacherPanel = not user.isAdmin() and user.isTeacher() and not user.isStudent()
if displayTeacherPanel:
showTeacherPanel()
Run Code Online (Sandbox Code Playgroud)
这可能看起来很愚蠢,但您可能还有另一种情况,当且仅当您显示教师面板或者用户默认情况下有权访问其他特定面板时,您只想显示另一个项目:
if displayTeacherPanel or user.canSeeSpecialPanel():
showSpecialPanel()
Run Code Online (Sandbox Code Playgroud)
尝试在不使用变量来存储和标记逻辑的情况下编写上述条件,不仅会得到非常混乱、难以阅读的逻辑语句,而且还会重复自己。虽然存在合理的例外情况,但请记住:不要重复自己 (DRY)。
简单明了,也通过了 pep8 检查:
if (
cond1 and
cond2
):
print("Hello World!")
Run Code Online (Sandbox Code Playgroud)
最近,我一直更喜欢allandany函数,因为我很少混合 And 和 Or 比较,这效果很好,并且具有通过生成器理解提前失败的额外优势:
if all([
cond1,
cond2,
]):
print("Hello World!")
Run Code Online (Sandbox Code Playgroud)
只需记住传递一个可迭代对象即可!传入 N 个参数是不正确的。
注意:any就像多次or比较,all就像多次and比较。
这与生成器理解很好地结合在一起,例如:
# Check if every string in a list contains a substring:
my_list = [
'a substring is like a string',
'another substring'
]
if all('substring' in item for item in my_list):
print("Hello World!")
# or
if all(
'substring' in item
for item in my_list
):
print("Hello World!")
Run Code Online (Sandbox Code Playgroud)
更多内容:生成器理解
再加上@krawyoti 所说的……长时间条件的气味是因为它们难以阅读和理解。使用函数或变量使代码更清晰。在 Python 中,我更喜欢使用垂直空格、括起括号,并将逻辑运算符放在每行的开头,这样表达式就不会像“浮动”一样。
conditions_met = (
cond1 == 'val1'
and cond2 == 'val2'
and cond3 == 'val3'
and cond4 == 'val4'
)
if conditions_met:
do_something
Run Code Online (Sandbox Code Playgroud)
如果需要多次评估条件(如在while循环中),则最好使用局部函数。
| 归档时间: |
|
| 查看次数: |
1074681 次 |
| 最近记录: |