1.列表生成式:
定义俩个变量:
list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c", "d", "e"]
想让 变为 a1 b2 c3 d4 e5 传统方式:
list3 = [] #定义一个空列表, 使用for 循环append 存进去
list3 = []
for x, y in zip(a,b):
list3.append(str(y) + str(x))
print(list3)
另一种方式直接:
c = [ str(x)+str(y) for x, y in zip(b, a) ] #定义一个列表生成试直接搞定,也可以加判断 if 这些等
print(c)
判断 数字必须大于2, 字母不等于 e
c = [ str(x)+str(y) for x, y in zip(b, a) if y >2 and x != "e"]
print(c)
2.字典方式
字典去重
dict1 = ["a", "b", "a", "c", "a", "c", "b", "d", "e", "c", "a", "c","a"] #进行去重,使用 dict 中set
print(set(dict1))
统计出字典中有多少一致的
dict1 = ["a", "b", "a", "c", "a", "c", "b", "d", "e", "c", "a", "c","a"]
dictset = set(dict1)
d = {}
for i in dictset :
d[i] = dict1.count(i) #进行循环统计 列表中多少个一致的
print(d)
安装 字典中统计的进行排序
dict2 = sorted(d.items(), key=lambda x: x[1], reverse=True) # 使用列表中sorted 进行倒叙 在使用reverse= True 进行反向排序
print(dict2 )
dict3= sorted(d.items(), key=lambda x: x[1],reverse=False)
print(dict3)