用函数重新设计文章单词出现次数程序
composition = '''This is my family. We have a father, a mother and two brothers.
My father is a doctor. He works in a hospital. My mother is a teacher.
She teaches English in a school. My older brother is a student. He studies in a university.
My younger brother is a child.He is only five years old.
We often go to the park together on Sundays.My best friend is John.
He is very tall and has short hair. He always wears a smile on his face.
He likes playing basketball and listening to music.
We often study together and help each other with our homework.
He is very kind and always ready to help others. I am very lucky to have him as my friend.'''# 用函数来做单次统计程序# 1.输出一次原始作文
# print# 2.字符串修改
def modify_composition(composition):str = composition.lower()for letter in str:if letter in '?,.':str = composition.replace(letter, '')return str# 3.单词统计
def count_words(str):str_list = str.split()myDict = {wd:str_list.count(wd) for wd in str_list}return myDictcomposition = modify_composition(composition)
res = count_words(composition)
print(res)
执行结果
列表转制(列表嵌套列表)
# 5 行 4 列
x = [[11, 12, 13, 14],[15, 16, 17, 18],[19, 20, 21, 22],[23, 24, 25, 26],[27, 28, 29, 30]]# 需求:访问x列表的每一个元素
# for i in range(0, len(x)):
# for j in range(0, len(x[i])):
# print(x[i][j], end="\t")# 行
row = len(x)
# 列
col = len(x[0])# y 列表是 4行 5列
y = [[],[],[],[]]
for i in range(col):for j in range(row):v = x[row - j - 1][col - i - 1]print(v, end="\t")print()
执行结果
代码调整
# 5 行 4 列
x = [[11, 12, 13, 14],[15, 16, 17, 18],[19, 20, 21, 22],[23, 24, 25, 26],[27, 28, 29, 30]]# 需求:访问x列表的每一个元素
# for i in range(0, len(x)):
# for j in range(0, len(x[i])):
# print(x[i][j], end="\t")# 行
row = len(x)
# 列
col = len(x[0])# y 列表是 4行 5列
y = [[],[],[],[]]
for i in range(col):for j in range(row):v = x[row - j - 1][col - i - 1]# print(v, end="\t")y[i].append(v)# print()print(y)
执行结果
列表螺旋输出
实现n行n列数组arr从外至内的顺时针螺旋输出,例如,对于如下的数组a,printArray(a)
原始数据是
x = [[1, 2, 3, 4],[12, 13, 14, 5],[11, 16.15, 6],[10, 9, 8, 7]]
双层循环:外层循环控制循环的次数,内层循环