product() 函数避免嵌套循环
list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]
for a in list_a:
for b in list_b:
for c in list_c:
if a + b + c == 2077:
print(a, b, c)
转换效果
from itertools import product
list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]
for a, b, c in product(list_a, list_b, list_c):
if a + b + c == 2077:
print(a, b, c)
# 70 2000 7
三元运算符
适用于if-else 条件在编程世界中无处不在。为了让简单的逻辑易于表达,Python 为我们提供了三元运算符。简而言之,它只允许将 if-else 条件放在一行中:
if a<b:
min = a
else:
min = b
min = a if a < b else b
字典相关
更新字典,字典添加键值对
# 更新字典
mydict = {1: "Python", 2: "JavaScript", 3: "Csharp"}
mydict.update({4: "Dart"})
print(mydict) # {1: 'Python', 2: 'JavaScript', 3: 'Csharp', 4: 'Dart'}
字符串相关
F-Strings:Pythonic 字符串格式化技术
pi = 3.1415926
print(f'Pi is approximately equal to {pi:.2f}')
# Pi is approximately equal to 3.14
id = 1 # need to print a 3-digit number
print(f"The id is {id:03d}")
# The id is 001
N = 1000000000 # need to add separator
print(f'His networth is ${N:,d}')
# His networth is $1,000,000,000
列表相关
两个列表的交并补差
l1 = [1,2,3]
l2 = [3,4,5]
def bing(l1,l2):
bing = list(set(l1)|set(l2))
print(bing)
def jiao(l1,l2):
bing = list(set(l1)&set(l2))
print(bing)
def bu(l1,l2):
bing = list(set(l1)^set(l2))
print(bing)
def cha(l1,l2):
bing = list(set(l1)-set(l2))
print(bing)
bu(l1,l2)
运行速度