首页 > 解决方案 > 替换子列表中的项目而不展平

问题描述

在以下列表中:

tab1 = [['D001', None, None, None, 'Donald Duck', 'Organise a meeting with Scrooge McDuck', 'todo',  None],
 ['D002', None, None, None, 'Mickey Mouse','Organise a meeting with Minerva Mouse', 'done',  None],
 ['D003', None, None, None, 'Mickey Mouse', 'Organise a meeting with Daisy Duck', 'todo',  None],
 [None, None, None, None, None, None, None, None]]

对于每个非空的子列表,我想用“...”替换 None 值

我试过了:

foo =[]
for row in tab1:
    if row[0] is not None:
        for cell in row:
            if cell is None:
                cell = "..."
            foo.append(cell)

但是 foo 给了我:

['D001',
 '...',
 '...',
 '...',
 'Donald Duck',
 'Organise a meeting with Scrooge McDuck',
 'todo',
 '...',
 'D002',
...

代替:

[['D001',
 '...',
 '...',
 '...',
 'Donald Duck',
 'Organise a meeting with Scrooge McDuck',
 'todo',
 '...',]
 ['D002',
...

标签: pythonpython-3.x

解决方案


你只需要有临时变量:

foo = []
for row in tab1:
    temp_list = []
    if row[0] is not None:
        for cell in row:
            if cell is None:
                cell = "..."
            temp_list.append(cell)
    foo.append(temp_list)

推荐阅读