Python十道基础编程题
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)