【上海校区】python常用用法

python 未结 0 99
汕头网站优化
汕头网站优化 2021-04-26 14:28
悬赏:13
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()))


相关标签:
回答
  • 消灭零回复
提交回复