python - 如何在 python 函数中包含布尔选项
问题描述
如何在我的 python 函数中包含布尔选项?例如,在 panda 的库中有一个方法 .sort_values() 有一个称为升序的参数,默认情况下为 True,但如果设置为 False,则该函数将进行不同的排序。该方法的详细信息对我的问题并不重要,如果您好奇,可以阅读 .sort_values() 的详细信息:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame .sort_values.html
关键是数据帧有一个参数 acsending 默认为 true Pandas.DataFrame.sort_values(self, by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last)
如何编写带有参数(如升序)的函数。假设我编写了一个名为 make_it_more 的函数,它接受一个整数或浮点 x 并向其加一。如果设置为 true 将返回 x+2 的选项。我将如何编写该函数?
def make_it_more(x, one_more=False):
y=x+1
if one_more==True:
y=y+1
return y
我如何编写 make_it_more 以便它知道只响应 one_more=True,.sort_values() 之类的函数是否检查特定字符串并在给出不匹配字符串时返回错误?
解决方案
使用is
,像这样:
def make_it_more(x, one_more=False):
amount_to_make_it_more_by = 2 if one_more is True else 1
return x + amount_to_make_it_more_by
否则你会遇到这样的问题:
>>> 1 == True
True
>>> 1 is True
False
推荐阅读
- html - 隐藏 cookie 横幅的 HTTP 标头
- sql - SQL 子查询 > 1 含义
- dart - list.elementAt(n) 和 list[n] 之间有什么区别吗
- android - 网络服务发现 错误的 IP 已解决
- sql-server - 为什么 SQL Server Management Studio 从复制的代码中获取这些语法错误
- r - 根据 YAML 标头(参数)中定义的选项运行不同的 Rchunk?
- python - PyQt5 消息框立即关闭
- macos - 在 macos 中,如果我使用自我证书签署我的应用程序并将该证书安装在目标机器中,是否有可能成为“已识别的开发人员”?
- c - C中的数组指针问题-数组仅包含最后一个值
- mysql - mysql中带有json的子查询