生活随笔
收集整理的這篇文章主要介紹了
(三)3-1 练习
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 把一個(gè)數(shù)字的list從小到大排序,然后寫(xiě)入文件,然后從文件中讀取出來(lái)文件內(nèi)容,然后反序,在追加到文件的下一行中
2. 分別把 string, list, tuple, dict寫(xiě)入到文件中
#!/usr/bin/env python
#coding:utf8import random
import codecs
def getList():l = []for i in range(10):num = random.randint(1,100)l.append(num)l.sort(reverse=False)print("隨機(jī)生成的列表由小到大排序:{0}".format(l))return ldef wFile(l,mode):with codecs.open("testList.txt",'{0}b'.format(mode)) as fd:if mode == "a":fd.write('\n')fd.write("{0}".format(l))
def rFile():with codecs.open("testList.txt",'rb') as fd:for line in fd.readlines():newL = line.lstrip('[').rstrip(']').split(',')newList = [int(i) for i in newL]newList.sort(reverse=True)print("反序后的列表是:{0}".format(newList))wFile(newList,'a')string1 = "123456789,hello world !"
print(type(string1))
list1 = ['a','b','c']
print(type(list1))
tuple1 = (1,2,"abc","efc")
print(type(tuple1))
dict1 = {"name":"cnblogs","age":"20"}
print(type(dict1))if __name__=="__main__":l = getList()wFile(l,'w')rFile()print("分別把 string, list, tuple, dict寫(xiě)入到文件中")wFile(string1,"a")wFile(list1,"a")wFile(tuple1,"a")wFile(dict1,"a")
代碼運(yùn)行結(jié)果:
<type 'str'>
<type 'list'>
<type 'tuple'>
<type 'dict'>
隨機(jī)生成的列表由小到大排序:[30, 46, 53, 53, 55, 65, 68, 83, 84, 95]
反序后的列表是:[95, 84, 83, 68, 65, 55, 53, 53, 46, 30]
分別把 string, list, tuple, dict寫(xiě)入到文件中
最終testList.txt寫(xiě)入的內(nèi)容
[
30,
46,
53,
53,
55,
65,
68,
83,
84,
95]
[95,
84,
83,
68,
65,
55,
53,
53,
46,
30]
123456789,hello world !
['a',
'b',
'c']
(1,
2,
'abc',
'efc')
{'age':
'20',
'name':
'cnblogs'}
?
轉(zhuǎn)載于:https://www.cnblogs.com/pythonlx/p/7756796.html
總結(jié)
以上是生活随笔為你收集整理的(三)3-1 练习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。