用函數重新設計文章單詞出現次數程序
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]]
雙層循環:外層循環控制循環的次數,內層循環