PEP 8没有提及切片运算符。使用复杂的表达式时,从我的理解,不像其他的运营商,它不应该有空白风格,格式化切片运算符
spam[3:5] # OK
spam[3 : 5] # NOT OK
包围这是否保留,即,其中一个被认为是更好的风格
1. spam[ham(66)//3:44+eggs()] 2. spam[ham(66) // 3: 44 + eggs()] 3. spam[ham(66) // 3 : 44 + eggs()] 4. something else?
PEP 8没有提及切片运算符。使用复杂的表达式时,从我的理解,不像其他的运营商,它不应该有空白风格,格式化切片运算符
spam[3:5] # OK
spam[3 : 5] # NOT OK
包围这是否保留,即,其中一个被认为是更好的风格
1. spam[ham(66)//3:44+eggs()] 2. spam[ham(66) // 3: 44 + eggs()] 3. spam[ham(66) // 3 : 44 + eggs()] 4. something else?
正如你已经提到,PEP8没有明确提到该格式的切片运算符,但spam[3:5]
肯定是越来越普遍,恕我直言,更具可读性。
如果pep8 checker是什么去了,:
前的空间将被标记了
[[email protected]]$ pep8 <(echo "spam[3:44]") # no warnings
[[email protected]]$ pep8 <(echo "spam[3 : 44]")
/dev/fd/63:1:7: E203 whitespace before ':'
...但这只是因为它假定:
是运营商定义文字字典和没有空间预计在运营商之前。 spam[3: 44]
因为这个原因而通过,但那看起来不正确。我想坚持spam[3:44]
。
嵌套算术运算有点棘手。你的3个例子中,只有2号一个通过验证PEP8:
[[email protected]]$ pep8 <(echo "spam[ham(66)//3:44+eggs()]")
/dev/fd/63:1:13: E225 missing whitespace around operator
[[email protected]]$ pep8 <(echo "spam[ham(66) // 3:44 + eggs()]") # OK
[[email protected]]$ pep8 <(echo "spam[ham(66) // 3 : 44 + eggs()]")
/dev/fd/63:1:18: E203 whitespace before ':'
不过,我觉得所有的上述困难的肉眼乍一看来解析。
出于可读性和遵守PEP8,我会亲自去为:
spam[(ham(66) // 3):(44 + eggs())]
或了解更多复杂的操作:
s_from = ham(66) // 3
s_to = 44 + eggs()
spam[s_from:s_to]
我同意你的第一个例子。对于后者:PEP 20。可读性计数。复杂切片表达式的语义上最重要的部分是切片运算符本身,它将表达式分为两部分,分别由人类阅读者和解释者分析。因此,我的直觉是,应该牺牲与PEP 8的一致性,以突出显示运算符:
。通过用空格包围它如实施例3问题是,如果省略了表达的两侧内的空格来增加可读性或不:
1. spam[ham(66)/3 : 44+eggs()]
与
2. spam[ham(66)/3 : 44 + eggs()]
我找到1.更快解析。
我看到切片在PEP8使用:
- Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes. startswith() and endswith() are cleaner and less error prone. For example: Yes: if foo.startswith('bar'): No: if foo[:3] == 'bar':
我不认为这是明确的,但备份你的(和我)的理解:
spam[3:5] # OK
至于用哪个在更复杂的情况下,我会使用#3。我不认为没有空间围绕头the- :
方法看起来在这种情况下,良好:
spam[ham(66)/3:44 + eggs()] # looks like it has a time in the middle. Bad.
如果你想:
更加凸现出来,不要牺牲运营间隔,多余的空格添加到在:
:
spam[ham(66)/3 : 44 + eggs()] # Wow, it's easy to read!
我不会使用#1,因为我喜欢的运营商间距和#2看起来太像字典key: value
语法。
我也不会称之为操作员。这对构建slice
对象特殊语法 - 你也可以做
spam[slice(3, 5)]