1.輸入日期,判斷這一天是這一年的第幾天 import datetime def day_of_year(): year = eval(input('請輸入年份:')) month = eval(input('請輸入月份:')) day = eval(input('請輸入天:')) date1 = ...
1.輸入日期,判斷這一天是這一年的第幾天
import datetime
def day_of_year():
year = eval(input('請輸入年份:'))
month = eval(input('請輸入月份:'))
day = eval(input('請輸入天:'))
date1 = datetime.date(year, month, day)
date2 = datetime.date(year, 1, 1)
return (date1 - date2).days + 1
2.打亂一個排好序的alist = [1, 3, 5, 7, 9]
import random
alist = [1, 3, 5, 7, 9]
random.shuffle(alist)
print(alist)
3.現有字典d = {'a':10, 'b':5, 'c':13, 'd':2},請根據字典的value值進行排序
d = {'a': 10, 'b': 5, 'c': 13, 'd': 2}
a = sorted(d.items(), key=lambda x: x[1])
print(a)
4.請反轉字元串"live"
print("live"[::-1])
5.將字元串"a:1|b:2|c:3|d:4"處理成字典
a = "a:1|b:2|c:3|d:4"
result = {}
for item in a.split('|'):
k, v = item.split(':')
result[k] = eval(v)
print(result)
6.給定兩個列表,找出它們相同的元素和不同的元素
list1 = [1, 2, 3]
list2 = [3, 4, 5]
print("交集:", set(list1) & set(list2))
print("差集:", set(list1) ^ set(list2))
7.設計實現遍歷目錄和子目錄,抓取.docx文件
from glob import iglob
def func(path, suffix):
for i in iglob(f'{path}/**/*{suffix}', recursive=True):
print(i)
if __name__ == '__main__':
func('D:/my_file', '.docx')
8.遍歷列表時刪除元素的正確做法
items = ['apple', 'banana', 'orange', 'pear', 'melon', 'grape']
# 遍歷在新的列表操作,刪除是在原來的列表操作
for item in items[:]:
items.remove(item)
print(items)
9. 統計一個文本中單詞頻次最高的10個單詞
import re
result = {}
with open('../doc/article.txt', 'r') as f:
for line in f:
word_list = re.findall('\w+', line)
for word in word_list:
if word in result.keys():
result[word] += 1
else:
result[word] = 1
#學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441
result = sorted(result.items(), key=lambda x: x[1], reverse=True)
print(result[:10])
10.寫出一個函數滿足以下條件
該函數的輸入是一個包含數字的list,輸出一個新的list,其中每個元素滿足以下條件:
- 該元素是偶數
- 該元素在原list中是在偶數的位置(index是偶數)
data_list = [1, 2, 5, 8, 10, 3, 18, 6, 20]
even_list = [data for data in data_list[::2] if data % 2 == 0]
print(even_list)