假设我们有该函数f
,并且我需要参数b
默认为空列表,但由于可变默认参数的问题而无法设置 b=[]。
其中哪一个最Pythonic,或者有更好的方法吗?
def f(a, b=None):
if not b:
b = []
pass
def f(a, b=None):
b = b or []
pass
Run Code Online (Sandbox Code Playgroud) 假设我有一个返回多个值的函数
import numpy as np
def add_and_raisepower(x, y):
"""
1) Add inputs **x** and **y** and return the result.
2) Raise **x** to the power of **y**, multiply this
result by an array of one's and return the result.
:type x: float
:param x: The first input number
:type y: float
:param y: The second input number
:rtype val1: float
:rtype val2: numpy.array(float)
"""
val1 = x + y
val2 = np.ones(100)*(x**y)
return val1, val2
Run Code Online (Sandbox Code Playgroud)
我关心的是:rtype:
文档字符串中的评论;如果函数返回多个值(如本示例所示),则应如何:rtype:
在文档字符串中编写(根据 …
PEP8 建议简化以下代码。
原本的
if a == True:
Run Code Online (Sandbox Code Playgroud)
建议
if a:
Run Code Online (Sandbox Code Playgroud)
然而,这两者并不相同。当我遵循 PEP8 的建议时我就明白了。尝试使用以下代码
import numpy as np
a = np.nan
if a == True:
print('a is True')
else:
print('a is not True')
if a:
print('a is True')
else:
print('a is not True')
Run Code Online (Sandbox Code Playgroud)
你会发现第一个告诉 a 不正确(正确),而第二个则错误地告诉 a 为真。
a is not True
a is True
Run Code Online (Sandbox Code Playgroud)
这个误导性建议的意义何在?
所以我有以下情况:
我有一个具有多个函数定义的模块.我想创建一个具有这些功能的类.
我只是想问哪条路最好?选项1
import ModuleWithFunctions
class bla(object):
ModuleWithFunctions = ModuleWithFunctions
Run Code Online (Sandbox Code Playgroud)
选项2
class bla(object):
import ModuleWithFunctions
Run Code Online (Sandbox Code Playgroud)
我知道选项2是针对PEP 8的,所以我假设人们会说选项1,但是,如果我希望所有内容都可用,那该怎么办?
bla.(function)
Run Code Online (Sandbox Code Playgroud)
代替:
bla.ModuleWithFunctions.(function)
Run Code Online (Sandbox Code Playgroud)
我怎么能用option1做到这一点?
我有这个非常简单的if块:
if obj_type == "domain":
key = "domain"
elif obj_type == "db_user":
key = "username"
else:
key = "name"
Run Code Online (Sandbox Code Playgroud)
这些可以转换为if表达式:
key = "domain" if obj_type == "domain" else "usernme" if obj_type == "db_user" else "name"
性能有任何优势吗?如果这不是一个因素,哪个应该是首选的可读性,PEP8合规性?
我没有清楚地理解pep8规则.如何拆分此行以处理"行太长错误"?请你能给我一些特别的信息吗?
messages.append(" ".join([json.loads(response)[0]["screen_name"], "unfollowed you"]))
Run Code Online (Sandbox Code Playgroud) 我一直在解决一个问题,但我不确定风格/功能明智,这通常被认为是最佳实践。
我有一个函数,可以对同一字符串进行多次检查,并根据该字符串返回一个值。使用堆叠式 if 语句或 if-elif-else 语句是更好的样式或功能吗?
例子:
def f(s):
if s == 'Hey':
return 'Sup.'
if s == "How's it going?"
return 'Not bad.'
return 'I have no idea what you said.'
Run Code Online (Sandbox Code Playgroud)
或者
def f(s):
if s == 'Hey':
return 'Sup.'
elif s == "How's it going?"
return 'Not bad.'
else
return 'I have no idea what you said.'
Run Code Online (Sandbox Code Playgroud) 我有这个代码块我想评论,但内联注释不起作用.我不确定PEP8指南适用于何处.建议吗?
if next_qi < qi + lcs_len \ # If the next qLCS overlaps
and next_ri < ri + lcs_len \ # If the next rLCS start overlaps
and next_ri + lcs_len > ri: # If the next rLCS end overlaps
del candidate_lcs[qi] # Delete dupilicate LCS.
Run Code Online (Sandbox Code Playgroud) while line_number < dictionary_elements_number and validation_bool == False:
Run Code Online (Sandbox Code Playgroud)
当我通过 pep8 运行它时出现此错误E712 comparison to False should be 'if cond is False:' or 'if not cond:'
是不是有点奇怪?
基本思想是写这样的一行:
url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) + '&text='.join(words)
Run Code Online (Sandbox Code Playgroud)
想要用PEP 8样式重写它,所以写了这样的代码:
url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) \
+ '&text='.join(words)
Run Code Online (Sandbox Code Playgroud)
其中哪一项是对的?
如果两者都不行,我想听听为什么,然后看看你会怎么写。
在以下场景中,哪一个是更好的设计,为什么?
A:
stop_words = ['com1', 'com2']
def clean_text(text_tokens, stop_words):
return [token for token in text_tokens if token not in stop_words]
clean_text(['hello', 'world', 'com1', 'com2'], stop_words)
Run Code Online (Sandbox Code Playgroud)
乙:
def clean_text(text_tokens):
stop_words = ['com1', 'com2']
return [token for token in text_tokens if token not in stop_words]
clean_text(['hello', 'world', 'com1', 'com2'])
Run Code Online (Sandbox Code Playgroud)
C:
STOP_WORDS = ['com1', 'com2']
def clean_text(text_tokens):
return [token for token in text_tokens if token not in STOP_WORDS]
clean_text(['hello', 'world', 'com1', 'com2'])
Run Code Online (Sandbox Code Playgroud)
添加了基于@MisterMiyagi 回答的 C 版本。
注1:在这种情况下,stop_words 是固定的,不会改变。
注2:stop_words 可以是一个很小的列表,也可以是一个很大的列表。
我创建了一些类,但是这些类的名称过长(eq:)NegativeChannelMetalOxideSemiconductorFieldEffectTransistor
。我想用\
python 换行,但是在这种情况下很难看。通常,在Python中,当代码太长时,使用\
来换行是一个不错的选择,但在这里行不通。我应该如何缩短或拆分这些行?
我可以知道在Python环境中,它符合PEP-8吗?
在全局变量之前导入:
import some_library
GLOBAL_VARIABLE = "something"
Run Code Online (Sandbox Code Playgroud)
或者导入之前的全局变量:
GLOBAL_VARIABLE = "something"
import some_library
Run Code Online (Sandbox Code Playgroud) pep8 ×13
python ×13
python-3.x ×3
python-2.7 ×2
class ×1
coding-style ×1
comments ×1
continuation ×1
docstring ×1
expression ×1
indentation ×1