二十多条超实用的Python一行代码 (上)
2021-01-26 本文已影响0人
七喜c4d
二十多条超实用的Python一行代码 (上)
给大家介绍并解释一些Python一行程序。可能有些你还不知道,但对你未来的Python项目很有用。
顺便给大家推荐一个Python编程交流的q裙,
大家在学习Python的道路上遇到了什么难题都可以一起讨论交流,集思广益,一同进步,Python学无止境。
1、交换两个变量

让我们通过交换两个变量作为一个简单的开始。 此方法是最简单、最直观的方法之一,无需使用临时变量或应用算术操作即可编写。
2、多个变量赋值

你可以使用逗号和变量一次性将多个值分配给变量。使用此技术,你可以一次分配多个数据类型。 你可以使用列表将值分配给变量。下面是将列表中的多个值分配给变量的示例。

3、列表中偶数的和
有很多方法可以做到这一点,但最好和最简单的方法是使用列表索引和sum函数。

4、从列表中删除多个元素 del是Python中用于从列表中删除值的关键字。

5、读取文件

这里我们使用列表来处理。 首先,我们打开一个文本文件,并使用for循环,逐行读取。 最后,使用strip删除所有不必要的空间。 通过使用列表功能,使得代码更简单,更短。

6、将数据写入文件

上面的代码首先创建一个文件data.txt(如果没有的话),然后它会在文件中写Python is awesome。
7、创建列表

我们也可以使用相同的方法创建一个字符串列表。

8、映射列表或类型转换整个列表
有时在我们的项目中,我们需要更改列表中所有元素的数据类型。你想到的第一个方法可能是使用循环,然后访问列表中的所有元素,然后一个接一个地更改元素的数据类型。 这个方法是老派的,在Python中我们有一个映射函数,可以为我们做这些工作。
