python小技巧

Posted songlin123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python小技巧相关的知识,希望对你有一定的参考价值。

同时遍历两个列表

1 nfc = ["Packers", "49ers"]
2 afc = ["Ravens", "Patriots"]
3 for i,j in zip(nfc,afc):
4     print(i,j)
Packers Ravens
49ers Patriots

列表转换成字符串

1 teams = ["Packers", "49ers", "Ravens", "Patriots"]
2 print(,.join(teams))
3 type(,.join(teams))
 
Packers,49ers,Ravens,Patriots
str

遍历列表同时得出序号和内容

1 teams = ["Packers", "49ers", "Ravens", "Patriots"]
2 for index, team in enumerate(teams):
3     print(index, team)

 

0 Packers
1 49ers
2 Ravens
3 Patriots
 

从字典中获得值

In [10]:
 
 
 
 
 
data = {‘user‘: 1, ‘name‘: ‘Max‘, ‘three‘: 4}
is_admin = data.get(‘admin‘, False)
print(is_admin)
 
 
 
False
 

Collections模块

 
  1 from collections import Counter
 2 print(Counter(‘hello‘)) 
 
Counter({‘l‘: 2, ‘h‘: 1, ‘e‘: 1, ‘o‘: 1})
 

Itertools模块

 
 
1 from itertools import combinations
2   
3 teams = ["Packers", "49ers", "Ravens", "Patriots"]
4 for game in combinations(teams, 2):
5     print(game)
6   

 

(‘Packers‘, ‘49ers‘)
(‘Packers‘, ‘Ravens‘)
(‘Packers‘, ‘Patriots‘)
(‘49ers‘, ‘Ravens‘)
(‘49ers‘, ‘Patriots‘)
(‘Ravens‘, ‘Patriots‘)

以上是关于python小技巧的主要内容,如果未能解决你的问题,请参考以下文章

提效小技巧——记录那些不常用的代码片段

zoho在线文档使用小技巧

Jquery 小技巧

小技巧

python常用代码

使 PHP 代码更加简洁的几个小技巧