python 常用方法积累
2018-07-31 本文已影响8人
ivywenyuan
-
operator.itemgetter
屏幕快照 2018-07-31 下午5.22.57.png
在排序中也很常用
屏幕快照 2018-07-31 下午5.25.51.png
- 随机值
from random import choice
from random import randint
a = choice([1,2,3,4,5]) # a是该列表中的任意一个
b = randint(1,5) #b是1~5之间的任意整数
- 读取文件
file_name1 = "...."
file_name2 = "..."
with open(file_name1) as f0:
for line in f0:
print line
with open(file_name1) as f1:
reader = csv.reader(f1)
for index,line in enumerate(reader)
print line
with open(file_name2) as f2:
j_data = json.load(f2)
for j_dict in j_data:
....
- 查找 list中的重复元素
some_list = ['a','b','a','a']
duplicate = set([ x for x in some_list if some_list.count(x) >1])
- 利用enumerate创建包含 指定索引值起始值的 元组列表
list_1 =['a','b','c']
list_2 = list(enumerate(list_1,1))
list_2 # [(1,'a'),(2,'b'),(3,'c')]