1 #!/usr/bin/env python3.5
2 # coding:utf-8
3 # 假定有一个列表,编写函数以一个列表值作为参数,返回一个字条串
4 # 该字符串包含所有表项,之间以逗号和空格分隔,并在最后一个值前插入 and
5 # 要求函数能处理传递给它的任何列表
6
7 # spam = input('please input a list:')
8 # 刚开始想从用户输入进行传递列表方式,但没成功
9
10 # 4.10.1
11 print("4.10.1 answer:")
12 def chlist_str(spam):
13 spam[-1] = 'and ' + spam[-1]
14 str_list = ', '.join(spam)
15 return str_list
16 new_str = chlist_str(['apple','banana','tofu','cats'])
17 print("convert str is:")
18 print(new_str)
19
20 # 4.10.2
21 # 这道题的目的在于进行嵌套列表的行列转换吧
22 print("4.10.2 answer:")
23 grid = [['.','.','.','.','.','.'],
24 ['.','o','o','.','.','.'],
25 ['o','o','o','o','.','.'],
26 ['o','o','o','o','o','.'],
27 ['.','o','o','o','o','o'],
28 ['o','o','o','o','o','.'],
29 ['o','o','o','o','.','.'],
30 ['.','o','o','.','.','.'],
31 ['.','.','.','.','.','.']]
32
33 # 第一种实现方法,因为这个列表的行列长度不相等,外层循环的换行数应该是子列表的长度。
34 for row in range(0,len(grid[0])):
35 for col in range(0,len(grid)):
36 # print(''.join(grid[col][row]),end='')
37 print(grid[col][row],end='')
38 print()
39
40 # 第二种实现方法,
41 for row in zip(*grid):
42 for col in row:
43 # print(''.join(col),end='')
44 print(col,end='')
45 print()