Python(3)—列表、字典使用
1、list
正则表达式的使用:https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
读取文件list
# 读文件 with open("test.txt", 'r') as fr: for i in fr: print(i) # 写文件 with open("test.txt", 'wr') as fr: fr.write("hello world!") # 列表 test_list = [1, 2, 3, 3, 2] test_list.append(0) for i in range(len(test_list)): print i, " ", test_list[i] # print(test_list.count(3)) test_list.sort() # reverse=True 填写参数标识逆序 for i in range(len(test_list)): print i, " ", test_list[i]
2、dict
遍历词典,添加元素
def test_dict(test_lists): vertical = {} for list in test_lists: for item in list: item_ext = item.get("ext", {}) types = item_ext.get("types", []) res_key = "other" if 0 in types or 5 in types: res_key = "news" elif 1 in types: res_key = "image" elif 14 in types: res_key = "video" vertical[res_key] = vertical.get(res_key, 0) + 1 return vertical
test_list = [1, 2, 3, 3, 2] try: print test_list[9] except: print "fail!" continue