Python出现的问题及相关编程方法总结
fw.write(list2)
TypeError: write() argument must be str, not list
类型转换:str转list与list转str
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。test_str = "".join(test_list) #使用分割
TypeError: sequence item 0: expected str instance, int found
tr2 = ",".join(str(x) for x in list2)+'\n'
至此,上述问题解决***************************************************************************************
对csv文件操作小结
读csv文件
with open('D:/trace analyse/a.csv','rt', encoding="utf-8") as csvfile: reader = csv.reader(csvfile) next(csvfile) #跳过第一行 for raw in reader: #对每一行处理 csvfile.close()
写csv文件
with open('D:/trace analyse/b.csv','w+',newline='') as wfile: writer = csv.writer(wfile) for key in dict: for value in dict[key]: writer.writerow([key, value, dict1.get(key+value)]) wfile.close()
***************************************************************************************
对txt文件操作小结
fw = open('D:/trace analyse/cputime-serires.txt','a') fw.write(str2) #这里不能写list类型 fw.close()
fr = open('D:/trace analyse/cputime-serires.txt','r') #按行读取数据 for str1 in fr.readlines():
***************************************************************************************
Random使用
random.randint(0,max) #产生一个0-max的整数
***************************************************************************************
List操作
求list全部元素的总和
sum(list2) #求list2全部元素的总和
对list中的元素执行统一操作
def Submethod(value): if value >= 1: value -= 1 return value list2 = list(map(Submethod,list2))
这种map方式,map中的function没法传递两个参数
map(square, list) #内置函数,对list每个元素求平方 map(lambda x: x ** 2, list) #自定义函数,同样是求平方 map(lambda x, y: x + y, list1, list2) #自定义函数,对两个list操作
这种map方式,对于条件语句不友好
***************************************************************************************

更多精彩