将嵌套列表值附加到新lis中

2024-05-08 15:40:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,它有一个嵌套的列表,我想访问它,然后根据一个条件附加到一个新的列表中。每个列表中有三个,我想知道如何分别访问它们。下面是它当前的样子[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]。一个更好地解释这一点的例子是,如果我想要第二列的数据,那么我的新列表将看起来像['B', 'E', 'H']。你知道吗

这是我目前所拥有的,但我现在相当困窘。。你知道吗

n = 0
old_list = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
new_list = []

for a, sublist in enumerate(old_list):
       for b, column in enumerate(sublist):
              print (a, b, old_list[a][b])
              if n == 0:
                     new_list.append(column[0])
              if n == 1:
                     new_list.append(column[1])
              if n == 2:
                     new_list.append(column[2])

print(new_list)         

我的电流输出。。你知道吗

0 0 A
0 1 B
0 2 C
1 0 D
1 1 E
1 2 F
2 0 G
2 1 H
2 2 I
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

我想要的输出。。你知道吗

n = 0
new_list = ['A', 'D', 'G']

n = 1
new_list = ['B', 'E', 'H']

n = 2
new_list = ['C', 'F', 'I']

谢谢你的帮助!你知道吗


Tags: in程序列表newforifcolumn条件
2条回答

另一个不使用*结构或zip()的解决方案:

for n in range(3):
    print('n = {}'.format(n))
    new_list = [sublist[n] for sublist in old_list]
    print('new_list = {}'.format(new_list))
>>> L = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
>>> columns = list(zip(*L))
>>> columns
[('A', 'D', 'G'), ('B', 'E', 'H'), ('C', 'F', 'I')]
>>> columns[1] # 2nd column
('B', 'E', 'H')

或者,如果希望将每列作为要修改的列表(因为zip返回不可变元组),则使用:

columns = [list(col) for col in zip(*L)]

相关问题 更多 >