1. 程式人生 > 其它 >實驗2 字串與列表

實驗2 字串與列表

實驗結論

實驗任務1,2,3

 1 # 基礎操作練習: 列表及列表推導式、格式化、型別轉換
 2 def task1():
 3     x = list(range(10))
 4 
 5     print('整數輸出1: ', end = '')
 6     for i in x:
 7         print(i, end=' ')
 8 
 9     print('\n整數輸出2: ', end = '')
10     for i in x:
11         print(f'{i:02d}', end = '-') # 指定每個整數輸出寬度佔兩列,不足兩列,左邊補0
12 
13
print('\n整數輸出3: ', end = '') 14 for i in x[:-1]: 15 print(f'{i:02d}', end = '-') 16 print(f'{x[-1]:02d}') 17 18 print('\n字元輸出1: ', end = '') 19 y1 = [str(i) for i in range(10)] # 函式str()用於把其它型別物件轉換成字串物件 20 print('-'.join(y1)) 21 22 print('字元輸出2: ', end = '') 23 y2 = [str(i).zfill(2) for
i in range(10)] # 方法.zfill()用於對字串進行格式化, 指定寬度為2列,不足左邊補0 24 print('-'.join(y2)) 25 26 # 把姓名轉換成大寫,遍歷輸出 27 def task2(): 28 name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 'cocteau twins'] 29 # 實現方式1 30 for name in name_list: 31 print(name.title()) 32 print
() 33 # 實現方式2 34 name_list_captilize = [name.title() for name in name_list] 35 print('\n'.join(name_list_captilize)) 36 37 def task3(): 38 name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 39 'cocteau twins'] 40 name_list=sorted(name_list) 41 i=1 42 for name in name_list : 43 print("%d."%(i),end=" ") 44 print(name.title()) 45 i+=1

實驗1,2,3截圖

實驗任務4

 1 def task4():
 2     text ="""The Zen of Python, by Tim Peters
 3 
 4 Beautiful is better than ugly.
 5 Explicit is better than implicit.
 6 Simple is better than complex.
 7 Complex is better than complicated.
 8 Flat is better than nested.
 9 Sparse is better than dense.
10 Readability counts.
11 Special cases aren't special enough to break the rules.
12 Although practicality beats purity.
13 Errors should never pass silently.
14 Unless explicitly silenced.
15 In the face of ambiguity, refuse the temptation to guess.
16 There should be one-- and preferably only one --obvious way to do it.
17 Although that way may not be obvious at first unless you're Dutch.
18 Now is better than never.
19 Although never is often better than *right* now.
20 If the implementation is hard to explain, it's a bad idea.
21 If the implementation is easy to explain, it may be a good idea.
22 Namespaces are one honking great idea -- let's do more of those!"""
23     words=0;i=1
24     while(i<len(text)):
25         if ((text[i-1]<="z" and text[i-1]>="a" or text[i-1]<="Z" and text[i-1]>="A")
26              and not(text[i]<="z" and text[i]>="a" or text[i]<="Z" and text[i]>="A" or text[i]=="'")
27              ):
28             words+=1;i+=1;continue
29         else:
30             i+=1
31     words+=1 #Add the last word
32     print("Linage:%d"%(text.count("\n")+1))#Add the last line
33     print("Words number:%d"%(words))
34     print(f"Charactor number:{len(text)}")
35     print("Space number:{}".format(text.count(" ")))

實驗任務4截圖

實驗任務5,6,7

def task5():
    book_list = [
                          ['靜靜的頓河','肖洛霍夫','金人', '人民文學出版社'],
                          ['大地之上','羅欣頓.米斯特里','張亦琦', '天地出版社'],
                          ['夜航西飛', '柏瑞爾.馬卡姆', '陶立夏', '人民文學出版社'],
                          ['來自民間的叛逆', '袁越', '','新星出版社'],
                          ['科技與惡的距離', '珍妮.克里曼', ' 詹蕎語', '墨刻出版社'],
                          ['燈塔','克里斯多夫.夏布特','呂俊君','北京聯合出版公司'],
                          ['小行星掉在下午','沈大成', '', '廣西師範大學出版社']
                        ]
    for i in range(len(book_list)):
        print(f"{i+1}.《{book_list[i][0]}》|{book_list[i][1]}|{book_list[i][3]}")

def task6():
    '''
某.csv格式資料檔案內資料如下:
99 81 75
30 42 90 87
69 50 96 77 89, 93
82, 99, 78, 100
    '''
    data = ['99 81 75', '30 42 90 87', '69 50 96 77 89 93', '82 99 78 100']
    Sum=0;i=0
    for team in data:
        numbers=team.split()
        for number in numbers:
            Sum+=eval(number);i+=1

    average=Sum/i
    print("%.2f"%(average))

def task7():
    words_sensitive_list = ['張三', 'V字仇殺隊', '']
    comments_list = ['張三因生命受到威脅正當防衛導致過失殺人,經辯護律師努力,張三不需負刑事責任。',
                     '電影<V字仇殺隊>從豆瓣下架了', '娛樂至死']
    for comments in comments_list:
        for words in words_sensitive_list:
            comments=comments.replace(words,"*"*len(words))
        print(comments)

實驗任務5,6,7截圖

 

實驗總結:

Python豐富的函式庫確實便於解決問題,但過多的函式代替了具體演算法的訓練必將導致對底層邏輯的疏忽及基礎程式設計能力的缺失。實驗應更加重視底層邏輯和基礎演算法方面的訓練。