python常用用法

1.range

In [3]: for i in range(4,0,-1):
   ...:     print(i)
   ...:     
4
3
2
1

2.sorted,lambda

dic = {('a', 10), ('b', 7), ('c', 7), ('d', 5), ('f', 5), ('e', 4), ('g', 3), ('h', 2), ('i', 2), ('j', 2)}
sorted(dic, key=lambda x:x[0],reverse=True)


结果:
[('j', 2),
 ('i', 2),
 ('h', 2),
 ('g', 3),
 ('f', 5),
 ('e', 4),
 ('d', 5),
 ('c', 7),
 ('b', 7),
 ('a', 10)]


sorted(dic, key=lambda x:x[1],reverse=True)

[('a', 10),
 ('b', 7),
 ('c', 7),
 ('d', 5),
 ('f', 5),
 ('e', 4),
 ('g', 3),
 ('j', 2),
 ('h', 2),
 ('i', 2)]

sorted(dic, key=lambda x:x[1],reverse=True)[:5]
取前5个
[('a', 10), ('b', 7), ('c', 7), ('d', 5), ('f', 5)]


lambda是一个匿名函数
g = lambda x : x+1
g(1)

等同于
def g(x):
   return x+1
g(1)

x[0]表示元组的第一个元素,sorted默认是升序,而reverse=True表示降序

3.dic.items()

# Python 字典 items() 方法以列表返回可遍历的(键, 值) 元组数组。
dic1 = {'a':10,'b':7,'c':7}
dic1.items()

dict_items([('a', 10), ('b', 7), ('c', 7)])

4.1.元组的join 


temp1 = ('所', ' ')
"".join(temp1).strip()

结果:

'所'


"".join(temp1)
结果:
'所 '

5.list of list里面的元组进行相应的拉平,from_iterable

from itertools import chain
temp2 = [[('业务部', '采购主管')], [('本人', '是从'), ('是从', '黄金珠宝'), ('黄金珠宝', '营业员')]]
temp3 = chain.from_iterable(temp2)
copus_word=[' '.join(item) for item in temp3]
# type(copus_word)
copus_word




['业务部 采购主管', '本人 是从', '是从 黄金珠宝', '黄金珠宝 营业员']

6.zip

dic = {'快速消费品_食品': 504, '业务部_采购主管': 44, '本人_是从': 650}
dict(zip(dic.values(),dic.keys()))
#type(zip(dic.values(),dic.keys()))

结果:
dic = {'快速消费品_食品': 504, '业务部_采购主管': 44, '本人_是从': 650}
dict(zip(dic.values(),dic.keys()))
#type(zip(dic.values(),dic.keys()))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值