当你开始使用 Python 编程时,那些不太明显的事情
我最初是用非常基础的语言进入编程世界的。四年前,我用 Python 创建了很多项目,尽管 Python 之禅说“应该有一种——最好只有一种——显而易见的方法来实现它”,但有些事情却并不那么显而易见。
一行条件。
我的旧代码有太多冗余代码,特别是条件代码:
if x < 56:
some = "Dafaq"
else:
some = "Nope"
没有什么比以下更简单了:
some = "Dafaq" if x < 56 else "Nope"
一行过滤列表。
Python 中最常见的情况之一是“过滤”列表。我以前的做法是:
a = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
b = []
for i in a:
if i >= 15:
b.append(i)
最好的方法:
a = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
b = [i for i in a if i >= 15]
一行总和列表值。
另一个最常见的做法是将列表的值相加。我以前的做法是:
amounts = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
total = 0
for i in amounts:
total += i
最好的方法:
amounts = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34]
total = sum(amounts)
在下一章中...
当您开始使用 Django 时,有些事情并不是那么明显......
文章来源:https://dev.to/henbaku/things-that-werent-so-obvious-when-you-starting-to-program-in-python-2fe