列表解析式
x = [[1,2,3], [4,5,6], [7,8,9]]
y = [num for i in x for num in i]
print(f"y = [num for i in x for num in i] :{y}") # y = [num for i in x for num in i] :[1, 2, 3, 4, 5, 6, 7, 8, 9]
# 都变成大写
fruit = ["apple", 'orange', "banana", "balabala"]
fruit = [x.upper() for x in fruit]
print(fruit)
# 挑选出以b开头的
b = []
for x in fruit:
if x.startswith("B"):
b.append(x)
print(b)
b = [x.lower() for x in fruit if x.startswith("B")]
print(b)
#output:
#['APPLE', 'ORANGE', 'BANANA', 'BALABALA']
#['BANANA', 'BALABALA']
#['banana', 'balabala']
# 遍历列表的三种方式
print("遍历列表的三种方式" )
a = ['a', 'b', 'c', 'd', 'e', 'f']
for i in a:
print(i)
for i in range(len(a)):
print(i, a[i])
for i, ele in enumerate(a):
print(i, ele)
字典合并技巧
#字典无需键或值对类型一致
a = {"aaa": 111, "bbb": 222, "ccc": 333}
b = {"ddd": 444, "eee": 555, "fff": 666}
# 合并字典
c = {}
for x in a:
#print(x) #x是字典的键
c[x] = a[x] #插入字典
for x in b:
c[x] = b[x]
print(c)
# 改变后
c = {**a, **b}
print(c)
字符串分割:
name = "zhang/san"
a,b = name.split("/")
print(a,b) #zhang san
b = name.split("/")
print(b) #['zhang', 'san']
字符串格式化操作
name = "Koma_zhe"
age = 24
print(" Myname is " + name + " and I am " + str(age))
print(" Myname is {} and I am {}".format(name, age))
print(" Myname is {1} and I am {0}".format(age, name))
# fstring
print(f" Myname is {name} and I am {age}")