python通用編程:一階段習題

練習一、打印金字塔

level = int(input('請輸入層數:'))
for i in range(1,level+1):
    for j in range(level-i):
        print(' ',end='')
    print('*'*(2*i-1))

在這裏插入圖片描述

練習二、嵌套列表去重

l = [

    {'name': 'albert', 'age': 18, 'sex': 'male'},

    {'name': 'james', 'age': 35, 'sex': 'male'},

    {'name': 'taylor', 'age': 25, 'sex': 'female'},

    {'name': 'albert', 'age': 18, 'sex': 'male'},

    {'name': 'albert', 'age': 18, 'sex': 'male'},

]

# print(set(l))  # 將報錯:unhashable type: 'dict'

# 方式一
s = set()
l1 = []
for item in l:
    val = (item['name'], item['age'], item['sex'])
    if val not in s:
        s.add(val)
        l1.append(item)
print(l1)

# 方式二、定義函數,既可以針對可以hash類型又可以針對不可hash類型(下一階段課程)
def func(items, key=None):
    s = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in s:
            s.add(val)
            yield item

print(list(func(l, key=lambda dic: (dic['name'], dic['age'], dic['sex']))))

練習三、統計單詞個數

對如下字符串進行統計:

s = 'hello albert albert say hello world world'

# 方式一
list1 = s.split()
dict1 = {}
for item in list1:
    if item in dict1:
        dict1[item] += 1
    else:
        dict1[item] = 1
print(dict1)

# 方式二
dict2 = {}
words = s.split()
for word in words:
    dict2[word] = s.count(word)
    #或者
    #dict2[word] = words.count(word)
print(dict2)

# 方式三
dict3 = {}
words = s.split()
for word in words:
    dict3.setdefault(word, s.count(word))
    print(dict3)

# 方式四  
from collections import Counter
cnt = Counter()
s='hello albert albert say hello world world'
l=s.split(' ')
for word in l:
    cnt[word] += 1
print(dict(cnt))

練習四、不改變順序地刪除文件重複行

import os
res_list = []
with open('a.txt') as f1,open('aa.txt','w') as f2:
    for line in f1:
        content = line.strip()
        if content not in res_list:
            res_list.append(content)
    f2.writelines('\n'.join(res_list))
os.remove('a.txt')
os.rename('aa.txt','a.txt')

練習五、指定路徑,拷貝文件

# 方式一
import sys
import shutil

# 把命令行中解釋器後空格分割的所有參數都存成列表
paths = sys.argv
shutil.copyfile(paths[1], paths[2]

保存該文件,在cmd中輸入如下命令,格式爲:
python py文件路徑 需拷貝文件路徑 新路徑

python C:\Users\Desktop\copy.py C:\Users\Desktop\cat.jpg D:\Files\cat.jpg
# 方式二,通過字節形式讀寫
import sys

list1 = sys.argv  

src_file_path = list1[1]
dst_file_path = list1[2]

with open(r'%s' % src_file_path, mode='rb') as src_f, \
        open(r'%s' % dst_file_path, mode='wb') as dst_f:
    for line in src_f:
        dst_f.write(line)

練習六、在文件中插入指定內容

# 方式一:
# 1、先把文件內容全部讀入內存
# 2、然後在內存中完成修改
# 3、再把修改後的結果覆蓋寫入原文件
# 缺點:會在文件內容過大的情況下,佔用過多的內存

with open('user.txt', mode='r', encoding='utf-8') as f:
    data = f.read()
    data = data.replace('馬一特', '馬一特[Albert]')

with open('user.txt', mode='w', encoding='utf-8') as f:
    f.write(data)

# 方式二:
# 以讀的方式打開原文件,以寫的方式打開一個新文件,一行一行的讀入文件內容
import os
 
with open('user.txt', mode='rt', encoding='utf-8') as read_f, \
         open('user.txt.swap', mode='wt', encoding='utf-8') as write_f:
     for line in read_f:
         if '馬一特' in line:
             line = line.replace('馬一特', '馬一特[Albert]')
    
        write_f.write(line)

os.remove('user.txt')
os.rename('user.txt.swap', 'user.txt')

# 方式三
import os
with open('aa.txt','r') as f1, open('bb.txt','w') as f2:
    content = f1.read()
    # 指定文本
    words = 'oppo'
    # 插值內容
    add = '[vivo]'
    pos = content.find(words)
    if pos != -1:
        content = content[:pos+len(words)] + add + content[pos+len(words):]
        f2.write(content) 
os.remove('aa.txt')
os.rename('bb.txt','aa.txt')

練習七、三級菜單

練習八、購物商城

見:
https://github.com/XJuly/Python_program

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章