python中列表生成试和字典去重

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)

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值