python的一些代码小技巧

1.定义一个很大的数

a = 1000000000
print(a)  # 1000000000
b = 10 * 10000 * 10000
print(b)  # 1000000000
c = 10_0000_0000
print(c)  # 1000000000

2.交换两个变量的值

a = 10
b = 20
c = a
a = b
b = c
print("a={}, b={}".format(a, b))  # a=20, b=10
a = 30
b = 40
b, a = a, b
print("a={}, b={}".format(a, b))  # a=40, b=30

3.连续不等式的写法

a = 85
if a >= 80 and a <= 100:
    print("优秀")
if 80 <= a <= 100:
    print("优秀")

4.字符串的乘法

print("==============================")
print("="*30)  # ==============================

5.列表拼接

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]
c = a + b
print(c)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

6.列表切片,左闭右开区间

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a[3:7])  # [4, 5, 6, 7]
print(a[3:-3])  # [4, 5, 6, 7]
print(a[-2])  # 9
print(a[:3])  # [1, 2, 3]
print(a[-4:])  # [7, 8, 9, 10]

7.元组的解包和打包

a = (1, 2, 3)
x, y, z = a
print("x={}, y={}, z={}".format(x, y, z))  # x=1, y=2, z=3
b = (z, y, x)
print(b)  # (3, 2, 1)

8.with语句

f = open("./test.txt", "r")
data = f.read()
print(data)
f.close()
with open("./test.txt", "r") as f:
    data = f.read()
print(data)

9.列表推导式

a = [1, 2, 3]
b = []
for e in a:
    b.append(e + 200)
print(b)
c = [e+100 for e in a]
print(c)

猜你喜欢

转载自blog.csdn.net/qq_37428140/article/details/122758240