Fed*_*rer 40 python for-loop if-statement idiomatic
我经常在这里看到某人的代码以及看起来像是"单行"的内容,这是一个单行语句,以传统的'if'语句或'for'循环的标准方式执行.
我已经google了,无法真正找到你能演出的那种?任何人都可以提出建议并最好举一些例子吗?
例如,我可以在一行中执行此操作:
example = "example"
if "exam" in example:
print "yes!"
Run Code Online (Sandbox Code Playgroud)
要么:
for a in someList:
list.append(splitColon.split(a))
Run Code Online (Sandbox Code Playgroud)
Ste*_*202 53
好,
if "exam" in "example": print "yes!"
Run Code Online (Sandbox Code Playgroud)
这是一个改进吗?不.您甚至可以if通过用分号分隔它们来向-clause 的主体添加更多语句.我建议不要这样做.
Bry*_*ore 39
我发现在大多数情况下,在一行上执行块子句是个坏主意.
作为一般性,它将降低代码形式的质量.高质量的代码形式是python的关键语言功能.
在某些情况下,python将在一行中提供方式,这些方式肯定更加pythonic.尼克D提到的列表理解中提到的事情:
newlist = [splitColon.split(a) for a in someList]
Run Code Online (Sandbox Code Playgroud)
虽然除非您需要专门的可重复使用列表,否则您可能需要考虑使用生成器
listgen = (splitColon.split(a) for a in someList)
Run Code Online (Sandbox Code Playgroud)
请注意,两者之间的最大区别在于您不能重复使用生成器,但使用起来效率更高.
现代版本的python中还有一个内置的三元运算符,可以让你做类似的事情
string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print
Run Code Online (Sandbox Code Playgroud)
要么
iterator = max_value if iterator > max_value else iterator
Run Code Online (Sandbox Code Playgroud)
有些人可能会发现这些比类似的if (condition):块更具可读性和可用性.
归结为它,它是关于代码风格的,与你正在研究的团队的标准是什么.这是最重要的,但总的来说,我建议不要使用一个行块,因为python中的代码形式非常重要.
Cor*_*sky 18
更一般地说,以下所有内容在语法上都是有效的:
if condition:
do_something()
if condition: do_something()
if condition:
do_something()
do_something_else()
if condition: do_something(); do_something_else()
Run Code Online (Sandbox Code Playgroud)
...等等.
for a in someList:
list.append(splitColon.split(a))
Run Code Online (Sandbox Code Playgroud)
您可以将以上内容重写为:
newlist = [splitColon.split(a) for a in someList]
Run Code Online (Sandbox Code Playgroud)
如果只有一行,Python允许你将indented子句放在同一行:
if "exam" in example: print "yes!"
def squared(x): return x * x
class MyException(Exception): pass
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99682 次 |
| 最近记录: |