python 二维列表

一、二维列表推导式

1.使用嵌套循环来实现二维列表

#创建二维列表
import pprint #这里导入了漂亮打印模块
list_2d=[['apples' for col in range(3)] for row in range(5)]
pprint.pprint(list_2d)

运行结果:

[['apples', 'apples', 'apples'],
 ['apples', 'apples', 'apples'],
 ['apples', 'apples', 'apples'],
 ['apples', 'apples', 'apples'],
 ['apples', 'apples', 'apples']]

这里有个推导式: list_2d=[ 'x' for col in range(cols)] for row in range(rows)]

2. 嵌套列表

#用列表推导式生成[[1,2,3],[4,5,6],[7,8,9]]
inner_list=[]
outer_list=[]
for i in range(1,10):
    inner_list.append(i)
    # print('inner',inner_list,i)
    if i %3==0: #i除以3的余数为0
        outer_list.append(inner_list)
        # print('outer',outer_list)
        inner_list=[]

print(outer_list)

运行结果:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

三、一个实例

tableData=[['apples','oranges','cherries','banana'],
           ['Alice','Bob','Carol','David'],
           ['dogs','cats','moose','goose']]

def printTables(data):
    new_table=[]
    for i in range(len(data[0])):
        table1=[]
        for j in range(len(data)):
            table1.append(data[j][i])
        new_table.append(table1)
    #print(new_table)
    return new_table

for list1 in printTables(tableData):
    for str1 in list1:
        print(str1.rjust(20,' '),end='')
    print()

结果是:

              apples               Alice                dogs
             oranges                 Bob                cats
            cherries               Carol               moose
              banana               David               goose

 

你可能感兴趣的:(Python)