在Python中有许多技巧和窍门,可以使你的编码更容易一些。在本教程中,我们要看一看你在使用Python时可能喜欢的一大堆技巧和窍门。其中包括Python条件运算符 (Ternary)、合并字典、帮助处理大数字的下划线、按特定顺序打印列表、如何使用上下文管理器、查找列表中最常见的项目、使用枚举函数、交换变量、使用help()、使用zip(),以及更多的主题。
Python 三元运算符
第一个要看的提示是 Python 中的三元运算符。它有时也被称为三元条件。三元运算是在Python的2.5版本中加入的。在某些情况下,Python的三元运算符很有用,它可以帮助缩短你的代码,或者使代码更加清晰。那么它是如何使用的呢?首先,让我们看看Python中一个简单的if/else条件。这是一个常见的模式,你检查一个条件是真还是假,然后根据这个条件的结果给一个变量赋值。
condition = True
if condition:
myvariable = 1
else:
myvariable = 0
print(f'myvariable is {myvariable}')
myvariable is 1
因为条件是真,所以变量被设置为 1。现在让我们把条件设为假,看看该变量如何被设为0。
condition = False
if condition:
myvariable = 1
else:
myvariable = 0
print(f'myvariable is {myvariable}')
myvariable is 0
三元论
一个更快的方法是使用Python中的三元组条件来写。这可以有效地将if/else结构变成一个简单的单行代码。在下面的代码中,我们可以看到它是如何工作的。仅仅因为它现在是一个单行代码并不意味着它更好。我们的目标是以一种简单的方式写出你和其他人都能理解的代码。很多时候,三元条件也同样容易阅读,尤其是当你习惯了它之后。所以,如果它能使代码更短,那就是一个额外的好处。
condition = True
othervariable = 1 if condition else 2
print(f'othervariable is {othervariable}')
othervariable is 1
condition = False
othervariable = 1 if condition else 2
print(f'othervariable is {othervariable}')
othervariable is 2
合并两个字典
下一个技巧是如何将两个Python字典合并成一个变量。这可以用Python 3.5中引入的双星号**操作符来完成。每个项目都被添加到新的字典中,重叠的条目使用后一个项目的值。这里是它的操作。
dictone = {'a': 1, 'b': 2, 'c': 3}
dicttwo = {'c': 4, 'd': 5, 'e': 6}
merged = {**dictone, **dicttwo}
print(merged)
{'a': 1, 'b': 2, 'c': 4, 'd': 5, 'e': 6}
大数字中的下划线作为逗号
这个提示涉及到你在 Python 中处理大数时的情况。在Python中,你不能用逗号来分割大数字。因此,你不能写一个像70,000,000,000这样的数字,而必须写成70000000000。看着这样的数字,很容易误认为是数字的大小。你可以使用的技巧是用下划线代替逗号的位置,Python允许这样做。
number1 = 70000000000
number2 = 70000000
print(number1 + number2)
70070000000
数学仍然会正确发生。然后你可以在Python中使用F字符串,像这样在输出中添加逗号。
number1 = 70_000_000_000
number2 = 70_000_000
sum = number1 + number2
print(f'{sum:,}')
70,070,000,000
指定一个列表的打印顺序
在Python中这个巧妙的小技巧允许你以你选择的任何顺序打印一个列表。
mylist = [10, 20, 30, 40]
a, b, c, d = mylist
print(a, b, c, d)
print(d, b, c, a)
10 20 30 40
40 20 30 10
利用 Python 上下文管理器
在Python中读写文件时,有几种方法可以完成这一任务。考虑一下这个文件和下面的代码。
file = open('fileondisk.txt', 'r')
file_contents = file.read()
file.close()
words = file_contents.split(' ')
word_count = len(words)
print(word_count)
12
上面的代码首先手动打开一个文件,然后读取该文件,接着手动关闭该文件。一旦我们得到了文件的内容,我们就用空格作为分隔符来分割单词,计算单词并打印出来。当你需要像这里看到的那样手动管理资源,如打开和关闭文件时,这是一个线索,可能有一个更好的方法来进行。更好的方法是通过使用上下文管理器。上下文管理器的目的是为你管理资源,所以你不需要手动处理。下面是使用与上下文管理器重写的代码,我想你会同意它是一个不错的结果。
with open('fileondisk.txt', 'r') as file:
file_contents = file.read()
words = file_contents.split(' ')
word_count = len(words)
print(word_count)
12
在一个列表中寻找最常见的项目
这个 Python 技巧告诉你如何找到一个列表中最常见的项目。下面的例子有一个字符串的列表。具体来说,在一个列表中有一堆蔬菜,我们想找到我们拥有最多的蔬菜。下面是如何做到这一点的。
veggies = ['broccoli', 'beans', 'eggplant', 'broccoli', 'cauliflower', 'squash']
print(max(set(veggies), key=veggies.count))
broccoli
如果出现平局,首先达到较高计数的项目获胜。
veggies = ['broccoli', 'beans', 'beans', 'eggplant', 'broccoli', 'cauliflower', 'squash']
print(max(set(veggies), key=veggies.count))
beans
Python中的枚举函数
下一个Python技巧是学习如何在Python中使用**enumerate()**函数。在其它语言中,当你使用for循环进行迭代时,你会自动获得一个索引,这样你就可以跟踪你在循环中的位置。Python 并没有这样的功能,所以有时你会看到像这样的代码来手动创建一个索引。
veggies = ['Broccoli', 'Brussels Sprouts', 'Cauliflower', 'Butternut Squash']
index = 1
for veggie in veggies:
print(index, veggie)
index += 1
1 Broccoli
2 Brussels Sprouts
3 Cauliflower
4 Butternut Squash
一个更好的方法是使用 enumerate() ,因为它是为这种类型的应用而设计的。默认情况下,当你使用 enumerate() 时,索引从 0 开始。 **start**参数并将其设置为1。
veggies = ['Broccoli', 'Brussels Sprouts', 'Cauliflower', 'Butternut Squash']
for index, veggie in enumerate(veggies, start=1):
print(index, veggie)
1 Broccoli
2 Brussels Sprouts
3 Cauliflower
4 Butternut Squash
互换两个变量
在Python中你可以做的一个很酷的技巧是轻松地交换变量。让我们看看这是如何工作的。首先,我们有两个带有一些数据的变量,把它们打印出来,得到我们所期望的东西。
tom, jerry = 'Tom', 'Jerry'
print(tom, jerry)
Tom Jerry
要颠倒每个变量的内容,我们所要做的就是像这样交换顺序。不需要设置临时变量。
tom, jerry = jerry, tom
print(tom, jerry)
Jerry Tom
上面的片段处理的是简单的字符串,整数也是一样的。
ten, twenty = 10, 20
print(ten, twenty)
ten, twenty = twenty, ten
print(ten, twenty)
10 20
20 10
一次在多个列表上循环
有时你可能想在 Python 中一次循环多个列表。这个提示将帮助你完成这种类型的事情。比方说,你有两个列表。你的目标是在第一次迭代中访问两个列表的第一个值,然后在第二次迭代中访问两个列表的第二个值,以此类推。有几种方法可以做到这一点。第一种是使用我们刚刚学到的enumerate()函数。
veggies = ['Broccoli', 'Brussels Sprouts', 'Cauliflower', 'Butternut Squash']
toppings = ['Cheese', 'Garlic', 'Olive Oil', 'Butter']
for index, veggie in enumerate(veggies):
topping = toppings[index]
print(f'{veggie} topped with {topping}')
Broccoli topped with Cheese
Brussels Sprouts topped with Garlic
Cauliflower topped with Olive Oil
Butternut Squash topped with Butter
所以我们可以看到一次在两个列表上循环的目的。每个列表的每个索引都与另一个列表的相应索引有某种联系。也许用 Python 中的**zip()**函数来实现这个目的是比较干净的。让我们看看它是如何工作的。
veggies = ['Broccoli', 'Brussels Sprouts', 'Cauliflower', 'Butternut Squash']
toppings = ['Cheese', 'Garlic', 'Olive Oil', 'Butter']
for veggie, topping in zip(veggies, toppings):
print(f'{veggie} topped with {topping}')
Broccoli topped with Cheese
Brussels Sprouts topped with Garlic
Cauliflower topped with Olive Oil
Butternut Squash topped with Butter
相当酷啊!但为什么只停留在两个列表上呢?让我们轻松地一次在三个列表上循环!
veggies = ['Broccoli', 'Brussels Sprouts', 'Cauliflower', 'Butternut Squash']
toppings = ['Cheese', 'Garlic', 'Olive Oil', 'Butter']
cooked = ['Fried', 'Baked', 'Steamed', 'Baked']
for veggie, topping, cook in zip(veggies, toppings, cooked):
print(f'{cook} {veggie} topped with {topping}')
Fried Broccoli topped with Cheese
Baked Brussels Sprouts topped with Garlic
Steamed Cauliflower topped with Olive Oil
Baked Butternut Squash topped with Butter
在 Python 中添加一个表情符号
如果不看看如何在你的 Python 代码中添加 Emoji,这个 Python 技巧列表就不完整。它是如何做到的呢?首先,你需要用pip install emoji来安装软件包,然后我们可以使用这样的代码。
import emoji
result = emoji.emojize('Python is :fire:')
print(result)
Python is 🔥
在Python中解压值
解包允许你一次分配许多值。它非常方便,允许你用简洁的语法表达大量的逻辑。让我们看看Python中解包值的几个例子。下面的代码从一个元组中解压了两个值,并把它们分别放在自己的变量中。你可以对任意多的值进行这样的操作。
one, two = (1, 2)
print(one)
print(two)
1
2
要解压数值但忽略某个特定的数值,你可以像这样使用下划线作为占位符。
one, _ = (1, 2)
print(one)
1
通常情况下,你希望在enumerate()左边的变量的数量与你的值的数量相同。 **=**左边的变量数量与右边要解压的数值数量相同。 =.这种映射应该是相等的。通过使用*操作符,有一点办法可以解决这个问题。使用这种方法,你可以把前两个值解压到它们自己的变量中,然后把其余的值分配给一个列表。
one, two, *three = (1, 2, 3, 4, 5)
print(one)
print(two)
print(three)
1
2
[3, 4, 5]
同样的下划线技巧也可以用来忽略某些值,就像我们上面看到的那样。
one, two, *_ = (1, 2, 3, 4, 5)
print(one)
print(two)
1
2
下面是这个技巧的另一个例子。
one, two, *three, four = (1, 2, 3, 4, 5)
print(one)
print(two)
print(three)
print(four)
1
2
[3, 4]
5
将句子中的每个词都大写
你可以在字符串上做很多技巧,但我最喜欢的一个技巧是简单地将title()方法应用于字符串,将字符串中每个词的第一个字母大写。比如说。
title = 'python tips and tricks'
print(title.title())
Python Tips And Tricks
使用Help()方法
想象一下,你的网络刚刚中断,你无法访问 Python 文档。你有一些关于你要使用的函数或模块的问题。不要害怕!help() 模块是你的朋友。事实上,对于我们的第一个技巧,我们将在help 上使用help()。观察一下。
help(help)
Help on _Helper in module site object:
class _Helper(builtins.object)
| Define the built-in 'help'.
| This is a wrapper around pydoc.help (with a twist).
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
在构建和调试时,有三个奇妙的函数可以帮助你在 Python 代码中导航。它们是 type(), id(),和 dir().它们的作用是什么?让我们看看 **help()**说。
help(type)
Help on class type in module builtins:
class type(object)
| type(object_or_name, bases, dict)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
|
| Methods defined here:
|
| __call__(self, /, *args, **kwargs)
| Call self as a function.
|
| __delattr__(self, name, /)
| Implement delattr(self, name).
|
| __dir__(self, /)
| Specialized __dir__ implementation for types.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __instancecheck__(self, instance, /)
| Check if an object is an instance.
|
| __repr__(self, /)
| Return repr(self).
|
| __setattr__(self, name, value, /)
| Implement setattr(self, name, value).
|
| __sizeof__(self, /)
| Return memory consumption of the type object.
|
| __subclasscheck__(self, subclass, /)
| Check if a class is a subclass.
|
| __subclasses__(self, /)
| Return a list of immediate subclasses.
|
| mro(self, /)
| Return a type's method resolution order.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __prepare__(...)
| __prepare__() -> dict
| used to create the namespace for the class statement
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __abstractmethods__
|
| __dict__
|
| __text_signature__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __base__ = <class 'object'>
| The base class of the class hierarchy.
|
| When called, it accepts no arguments and returns a new featureless
| instance that has no instance attributes and cannot be given any.
|
| __bases__ = (<class 'object'>,)
|
| __basicsize__ = 440
|
| __dictoffset__ = 132
|
| __flags__ = 2148291584
|
| __itemsize__ = 20
|
| __mro__ = (<class 'type'>, <class 'object'>)
|
| __weakrefoffset__ = 184
help(id)
Help on built-in function id in module builtins:
id(obj, /)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
help(dir)
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
使用传递
你可能见过一些 Python 代码,其中定义了一个函数或类,但它只有一个 **pass**在里面。这到底是怎么回事呢?在 Python 中,pass关键字可以用来表示什么都不发生。它被用在一个函数、类或循环中,在那里你只想把代码存根出来。Pass 被用来快速添加实现的东西。下面是一个Veggie()类,完全不做任何事情。
class Veggie():
pass
veggie = Veggie()
获取/设置对象属性
Python 类对象很有趣,因为你可以动态地给一个对象添加属性和值。让我们看看这是如何工作的。
class Veggie():
pass
veggie = Veggie()
veggie.color = 'Green'
veggie.name = 'Broccoli'
print(f'{veggie.name} is {veggie.color}')
Broccoli is Green
有趣的是!颜色和名字的属性在类中没有任何定义,我们只是通过使用它们将它们变为现实。
如果我们想,我们可以使用另一个变量的值来设置另一个属性。这是用**setattr()**这样做的。
key = 'season'
value = 'Spring'
setattr(veggie, key, value)
print(veggie.season)
Spring
如果要通过一个变量的值来获取属性,我们可以使用getattr() 。
key = 'season'
value = 'Spring'
setattr(veggie, key, value)
season = getattr(veggie, key)
print(season)
Spring
当你在一些数值上进行循环时,这两个函数很有用,这些数值是你想从一个对象中获取的属性。让我们看看这在代码中意味着什么。考虑这个字典,它有一些键和值。
veggie_info = {'color': 'Orange', 'name': 'Butternut Squash'}
假设我想循环这个字典中的项目并把它们作为属性添加到蔬菜对象中。通过下面的代码,我们在字典上循环,每个键都变成了一个属性,每个值都被分配给对象上的那个属性。如果没有**setattr()**函数,这就很难做到。
veggie_info = {'color': 'Orange', 'name': 'Butternut Squash'}
for key, value in veggie_info.items():
setattr(veggie, key, value)
print(f'{veggie.name} is {veggie.color}')
Butternut Squash is Orange
我们可以使用getattr() 来实现另一个方向。
for key in veggie_info.keys():
print(getattr(veggie, key))
Orange
Butternut Squash
检查子串
检查一个字符串是否存在于另一个字符串中是你在程序中最常做的事情之一。这在Python中很容易做到,使用 **in**和 not in.
string = 'Python Tips Tricks Hacks And Cracks'
if 'Tricks' in string:
print('In the string!')
In the string!
正如你所看到的,这是对大小写敏感的。
string = 'Python Tips Tricks Hacks And Cracks'
if 'tricks' in string:
print('In the string!')
else:
print('Not in the string...')
Not in the string...
not in操作符的作用是这样的。
string = 'Python Tips Tricks Hacks And Cracks'
if 'eggs' not in string:
print('Eggs are not in the string')
Eggs are not in the string
安全输入
大多数 Python 教程都会让你使用某种形式的输入来从用户那里获得数据。我相信你已经看到了与此相似的代码。
name = input('What is your name?: ')
password = input('What is your password?: ')
这样做的问题是,你那爱管闲事的同事可能正在看着你,而你刚刚分享了你在公司网络、Facebook、Twitter、个人电子邮件、Tik Tok 和你的约会档案中使用的密码。这可不是好事。解决办法是使用getpass()!
from getpass import getpass
name = input('What is your name?: ')
password = getpass('What is your password?: ')
现在,你的密码被混淆了,没有人,尤其是你那爱管闲事的同事,可以看到它!
使用Pycharm
拥有一个好的IDE或集成开发环境会帮助你写出更好的Python。Pycharm是编写Python的最强大的工具之一,它将帮助你进行代码提示、代码格式化、调试、重构等等。专业版是一个付费工具,然而,社区版是免费的,而且几乎同样强大。
使用Visual Studio Code
Pycharm不是你的菜?不用担心,你可以使用Visual Studio Code,并利用许多提供优秀Python支持的扩展。Visual Studio Code是100%免费的,是Python的绝佳工具。
使用Jupyter Notebook
Jupyter Notebook是另一个使用Python的绝佳环境。你可以用它来测试简单的Python代码片段,或者用matplotlib之类的东西来做科学演示。按照我们关于如何安装Jupyter的指南了解更多信息。
在Python中检查一个列表是否为空
在Python中,你可以用几种方法来检查一个列表是否为空。这里有一些例子。
thelist = []
if not thelist:
print('That list is empty')
That list is empty
thelist = [];
if len(thelist) == 0:
print('Empty List!')
else:
print('Not Empty!')
Empty List!
thelist = [];
if bool(thelist) == False:
print('Empty List!')
else:
print('Not Empty!')
Empty List!
按值给字典排序
要按值对一个字典进行排序,你可以在 Python 中使用lambda 函数。注意,这种方法使最初的 dictionary 保持不变。但是我们可以将排序后的结果赋给一个新的变量并对其进行检查。
mydictionary = {'random': 7, 'key': 5, 'in': 3, 'the': 1, 'dictionary': 2, 'so': 4, 'fun': 6}
sortedbyval = {key: value for key, value in sorted(mydictionary.items(), key=lambda item: item[1])}
print(sortedbyval)
print(mydictionary)
{'the': 1, 'dictionary': 2, 'in': 3, 'so': 4, 'key': 5, 'fun': 6, 'random': 7}
{'random': 7, 'key': 5, 'in': 3, 'the': 1, 'dictionary': 2, 'so': 4, 'fun': 6}
扁平化一个列表
如果你有几个列表存储在一个变量中,你可以像这样把这些列表扁平化为一个列表。
manylists = [[1, 2, 'three'], ['four', 5, 6], [7, 'eight', 9]]
flattened = [item for sublist in manylists for item in sublist]
print(manylists)
print(flattened)
[[1, 2, 'three'], ['four', 5, 6], [7, 'eight', 9]]
[1, 2, 'three', 'four', 5, 6, 7, 'eight', 9]
如果 __name__ == "__main__": for?
你在 Python 中经常看到这行代码。那么它是做什么的呢?这里有一个 Python 文件的例子,它把一个文本文件复制到另一个文本文件。注意if __name__ == '__main__'的使用。
def main():
infile = open('fileondisk.txt', 'r')
outfile = open('copy_of_fileondisk.txt', 'w')
while True:
buf = infile.read(10240)
if buf:
outfile.write(buf)
print('.', end='', flush=True)
else:
break
outfile.close()
print('ndone.')
if __name__ == '__main__': main()
每当 Python 解释器读取一个源文件时,它都会设置一些特殊的变量,如 __name__,然后执行文件中的所有代码。Python 中的每个模块都有一个特殊的属性,叫做 __name__.属性的值 **__name__**属性的值在模块作为主程序运行时被设置为 '__main__'。
否则,属性的值 **__name__**的值被设置为包含模块的名称。
这种行为影响了在Python中运行模块的代码。如果你直接运行一个 Python 文件,__name__ 变量被设置为 __main__。然而,如果你导入一个 Python 文件而不是直接运行它,该文件的 __name__ 变量会被设置为文件的名称。在这一点上,这就是它的模块名称。如果文件没有被导入,则运行 main() 函数。
反转一个字符串
这个Python的小技巧是将一个字符串完美地反转。
mystring = 'Everybody wants to rule the world'
reversestring = mystring[::-1]
print(reversestring)
dlrow eht elur ot stnaw ydobyrevE
从一个列表中制作一个字符串
Python 中的 join() 函数可以从一个列表中取出一个字符串,像这样。
items = ['Welcome', 'to', 'your', 'life']
stringy = ' '.join(items)
print(stringy)
Welcome to your life
打印一个模块的路径
要打印一个导入的模块的路径,只需将模块的名称传递给 print() 函数。
import requests
print(requests)
<module 'requests' from 'C:\python\vrequests\lib\site-packages\requests\__init__.py'>
打印一个变量的内存使用情况
**.getsizeof()**函数将输出一个特定变量或对象的内存使用情况。请注意,在这个例子中,小字符串使用的内存较少,大字符串使用的内存较多。
import sys
wow = 'This is so cool'
print(sys.getsizeof(wow))
wowow = '''
This is so cool This is so cool This is so cool
This is so cool This is so cool This is so cool
This is so cool This is so cool This is so cool
'''
print(sys.getsizeof(wowow))
40
170
链式变量赋值
你可以在Python中通过链式赋值的方式创建多个变量,这些变量都引用同一个对象。
language = programming = tips = tricks = 'Python'
print(language, programming, tips, tricks)
Python Python Python Python
比较可以被链起来
你可以把比较连在一起,组成一个单一的Python表达式。
thenum = 100
if 200 > thenum == 100:
print('Chained comparison in action')
Chained comparison in action
你可以一次对一个以上的变量进行比较,但事情开始变得有点混乱,所以要小心处理这个问题。
thenum = 100
othernum = 'string'
if 200 > thenum == 100 > len(othernum) > 1:
print('Chained comparison in action')
Chained comparison in action
从字典中获取一个值
这个 Python 技巧是关于从一个字典中获取一个值。如果我们有一个价格字典,而我们只想要一个对象的价格,但我们不确定那个对象是否在字典中,我们如何解释呢?你需要在这样使用该值之前进行检查。
prices = {
'Coffee': 3.50,
'Burrito': 9.25
}
if 'Coffee' in prices:
price = prices['Coffee']
else:
price = 2.00
print(f'The coffee costs {price:.2f}')
一个更好的方法是使用**.get()**方法来做这件事。
prices = {
'Coffee': 3.50,
'Burrito': 9.25
}
price = prices.get('Coffee', 2.00)
print(f'The coffee costs {price:.2f}')
The coffee costs 3.50
第二种方法将4行代码减少到1行,如果咖啡不存在于字典中,则为它设置一个默认值。
在 For 循环中使用 Else
在 Python 中,你可以将else语句与for循环结合使用。要看这个技巧是如何工作的,首先我们看一下我们要通过这个提示来改进的代码。
needle = 'd'
haystack = ['a', 's', 'd', 'f']
found = False
for letter in haystack:
if needle == letter:
print('Found it!')
found = True
break
if not found:
print('Did not find needle.')
Found it!
更好的方法是使用for/else,正如我们在这里看到的。
needle = 'd'
haystack = ['a', 's', 'd', 'f']
for letter in haystack:
if needle == letter:
print('Found it!')
break
else:
print('Did not find needle.')
Found it!
在 Try/Except 块中使用 Else
Python 有一个很酷的技巧,让你在 try/except 块中使用 else。首先,我们看到我们将用这个技巧改进的代码。
try:
result = 25 / 0
except:
print('You can not divide by zero')
You can not divde by zero
如果我们要除以5,并且仍然使用结果呢?为此,使用一个简单的else,像这样。
try:
result = 25 / 5
except:
print('You can not divide by zero')
else:
print(result)
5.0
在Jupyter笔记本中从上到下为所有单元格重新编号
如果你的Jupyter笔记本中有很多单元格,而在添加单元格的过程中,你把它们放在了现有单元格的上方或下方,那么你的单元格就会从上到下无序地编号。如果你想把Jupyter中的单元格从上到下重新编号,你可以选择Kernel->Restart & Run All。
检查两个列表的匹配情况
如果你有两个数据列表,想看看两个列表中都有哪些项目,你可以使用这个技巧。
calls = ['TSLA', 'AAPL', 'BA', 'LK', 'BAC', 'GE', 'SDC', 'OXY', 'ZM', 'JPM', 'TLRY', 'ROKU', 'MSFT', 'LYFT', 'C', 'MGM', 'XOM', 'PBR', 'SGMS', 'ABT', 'SQ', 'T', 'MU', 'MCD', 'VALE', 'VIAC', 'AMRN', 'UBER', 'M', 'GILD']
puts = ['TSLA', 'BA', 'OXY', 'LK', 'CZR', 'SQ', 'BBBY', 'TWTR', 'F', 'TLRY', 'CCL', 'MGM', 'DAL', 'BAC', 'UBER', 'JPM', 'AAL', 'AMRN', 'MRVL', 'FB', 'M', 'MET', 'MU', 'CGC', 'BABA', 'HAL', 'HSBC', 'AMZN', 'AAPL', 'IQ']
inboth = set(calls) & set(puts)
print(inboth)
{'BAC', 'AMRN', 'SQ', 'M', 'MU', 'MGM', 'BA', 'UBER', 'TSLA', 'LK', 'AAPL', 'TLRY', 'OXY', 'JPM'}
Python打印没有换行
Python中的print()函数在每次调用时都会自动添加一个换行。因此,如果你在一个循环中使用 print() ,最后会出现很多换行符。要停止这种行为,你可以使用这段代码。
print('A string', end='')
使用Python飞行
Python是一种神奇的语言。事实上,你只需用一行代码就可以飞行。
import antigravity
运行你放入这段代码的Python文件,看看会发生什么😃。
学习Python的禅
Python 中的另一个单行技巧是学习 Python 的禅。怎么做呢?像这样。
import this
在Iterables上使用map()函数
result = list(map(lambda x: x[0].upper(), ['red', 'green', 'blue']))
print(result)
['R', 'G', 'B']
双参数Lambda函数
在前面的例子的基础上扩展,多个参数可以被传递给lambda,这样函数就可以在任意数量的迭代变量上操作。
result = list(map(lambda x, y: str(x) + ' ' + y + 's', [10, 20, 30], ['Pepper', 'Tomato', 'Leek']))
print(result)
['10 Peppers', '20 Tomatos', '30 Leeks']
Python技巧和窍门总结
如果你看完了所有这些Python编程语言的技巧和窍门,那么你很可能有一个钢铁般的注意力,恭喜你!在Python编程中获得乐趣。祝你在Python中编程愉快👍
