Python五种实用的小技巧
小白学视觉
共 5921字,需浏览 12分钟
·
2021-04-19 10:18
点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达
本文转自:视学算法
最开始学 Python 时,如果我能掌握这些方法,那么代码看起来会更加优美。
字符串运算
列表推导式
lambda 和 map()
单行条件语句
zip()
>>> my_string = "Hi Medium..!"
>>> print(my_string * 2)
Hi Medium..!Hi Medium..!
>>> print(my_string + " I love Python" * 2)
Hi Medium..! I love Python I love Python
>>> print(my_string[::-1])
!..muideM iH>>> my_list = [1,2,3,4,5]
>>> print(my_list[::-1])
[5, 4, 3, 2, 1]
>>> word_list = ["awesome", "is", "this"]
>>> print(' '.join(word_list[::-1]) + '!')
this is awesome!
>>> def stupid_func(x):
>>> return x**2 + 5
>>> my_list = [1, 2, 3, 4, 5]
>>> new_list = []
>>> for x in my_list:
>>> if x % 2 != 0:
>>> new_list.append(stupid_func(x))
>>> print(new_list)
[6, 14, 30]
>>> my_list = [1, 2, 3, 4, 5]
>>> print([stupid_func(x) for x in my_list if x % 2 != 0])
[6, 14, 30]
>>> for item in list:
>>> if conditional:
>>> expression
>>> print([x ** 2 + 5 for x in my_list if x % 2 != 0])
[6, 14, 30]
>>> stupid_func = (lambda x : x ** 2 + 5)
>>> print([stupid_func(1), stupid_func(3), stupid_func(5)])
[6, 14, 30]
>>> my_list = [2, 1, 0, -1, -2]
>>> print(sorted(my_list))
[-2, -1, 0, 1, 2]
>>> print(sorted(my_list, key = lambda x : x ** 2))
[0, -1, 1, -2, 2]
>>> print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6])))
[4, 10, 18]
>>> x, y = [1, 2, 3], [4, 5, 6]
>>> z = []
>>> for i in range(len(x)):
>>> z.append(x[i] * y[i])
>>> print(z)
[4, 10, 18]
>>> x = int(input())
>>> if x >= 10:
>>> print("Horse")
>>> elif 1 < x < 10:
>>> print("Duck")
>>> else:
>>> print("Baguette")
print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
>>> first_names = ["Peter", "Christian", "Klaus"]
>>> last_names = ["Jensen", "Smith", "Nistrup"]
>>> print([' '.join(x) for x in zip(first_names, last_names)])
['Peter Jensen', 'Christian Smith', 'Klaus Nistrup']
交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~
评论