五个你不知道的Python技巧之减少代码行

在编码时减少行距是一种在竞争性编程中进行编码时有用的技术。在黑客马拉松或Google Kickstart等大型编程竞赛中,许多学生和编码人员都面临时间不足的问题。如果您是像这样使用编程语言的编码人员,Python那么您来对地方了。在本文中,我将讨论一些技巧和python中的内置函数,这些技巧在比赛或日常生活中对编码有帮助。

1.列表理解

列表理解是在python中创建列表时减少代码行的最佳方法。它将多行代码转换为单行代码。使用列表推导的语法是

newlist = [expression for item in iterable if condition == True]

例如:

# define the list of super heros
super_heros = ['Iron Man', 'Captain America', 'Super Man', 'Wonder Women']
# this is used to extract the marvels super hero from the super heros list
marvel = [marvel_hero for marvel_hero in super_heros if marvel_hero == 'Iron Man' or marvel_hero == 'Captain America']
# print the resulting marvel list
print(marvel)

2. Lambda函数

Lambda函数是一种非常有用的方法,它只需一行代码即可写下函数,而不是写下那么多行。当您在另一个函数中使用这些函数时,lambda函数的真正功能就会发挥作用。它也被称为匿名函数。使用lambda函数的语法

lambda arguments : expression

例如:

# define the lambda function
cube = lambda x: x**3
# print the result
print(cube(3)

3.交换变量

在进行竞争性编程时,交换是最常见的概念。在大多数数据结构中,也使用交换。在python中,执行交换的方式要容易得多,并且如果在执行交换时发现任何困难,也不会造成混淆。我将向您展示两种方式,即交换在python和其他语言中的执行方式。

在像C和C ++这样的语言中,执行交换

int a = 10;
int b = 20;
int temp = a;
a = b;
b = temp;

在python中,您可以执行交换

a = 10
b = 10
a, b = b, a

4.倒转清单

执行竞争性编程时,将列表反转用于不同类型的问题。许多学生使用for循环来反转列表,这会增加程序的复杂性,有时在调试代码时会引起混淆。Python允许您仅用一行代码即可反转列表,而无需使用for循环。例如:

#define the list
number_list = [1, 2, 3, 4, 5, 6]
# reverse the list using slicing
number_list[::-1]
# print the list
print(number_list) #[6, 5, 4, 3, 2, 1]

5.迭代列表

每当涉及到与迭代有关的问题时,我们大多数人都会尝试使用较长的语法,如果问题较大并且包含,则有时会花费很多时间nexting for loops。Python允许您在不使用旧式语法的情况下迭代列表。例如:

# define the list
car_list = ['Toyota', 'Maruti', 'BMW', 'Honda']
# iterate the car_list
for car in car_list:
# print each car from the list
       print(car)


在这里还是要推荐下我自己建的Python学习群:721195303,群里都是学Python的,如果你想学或者正在学习Python ,欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2021最新的Python进阶资料和零基础教学,欢迎进阶中和对Python感兴趣的小伙伴加入!

猜你喜欢

转载自blog.csdn.net/aaahtml/article/details/113028958