繁体   English   中英

如何为PyCharm教程代码简化此过程?

[英]How can I simplify this for a PyCharm tutorial code?

我在线上正在做一些教程,并且正在使用PyCharm(一个出色的IDE顺带一提),但是它表明我可以简化if语句

这仅是我所知,仅此而已

如果len(tasks)== []:

建议说:表达可以简化。 此检查检测与布尔文字的相等比较。

len(tasks) == []将始终为False 您可能意味着len(tasks) == 0 通常只用作

if not tasks:
    do_stuff()

真值测试文档可能会有所帮助。

你可以做

if tasks:
    # do something

如果tasks列表为空[]或为None ,则它将评估为false。


从PEP8指南

对于序列(字符串,列表,元组),请使用空序列为假的事实。

https://www.python.org/dev/peps/pep-0008/#id51

len()是Python中的内置函数 这是文档对len()函数的解释。

返回对象的长度(项目数)。 参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集合)。

因此, len()函数始终返回整数值。

>>> _list = []
>>> len(_list)
0  # It's 0, because it's an empty list.
>>> len(_list) == []
False  # Yes, because 0 is not equal to list
>>> 0 == []
False  # Same as before, len(_list) always return 0

我认为您正在检查list是否为空,可以通过这种方式轻松完成。

if tasks:  # or len(tasks) != 0
    # do something when list has one or more values:
else:
    # do something when list is empty

您可以从如何检查列表是否为空中参考更多信息 题。

if not tasks:
   do_stuff()

您可以在数组上直接应用not运算符,以检查数组是否为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM