替换子列表中的项而不展平

2024-09-21 04:39:53 发布

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

在以下列表中:

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)

但是富给了我:

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

而不是:

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

Tags: none列表withcelltodorowduckmeeting
3条回答

您只创建了一个列表,而不是一个列表列表:

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

print(bar)

您只需要有临时变量:

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)

使用嵌套列表并仅在列表中有非None值时替换值:

输出=[[y if y else'…'for y in x]if any(x)else[y for y in x]for x in tab1]

将其拆分以便于分析:

首先,更改列表中的None值:

a = ['A','B',None,'C','D',None]
# if we have a value in y leave it alone, otherwise change it to '...'
a = [y if y else '...' for y in a]
# a is now ['A','B','...','C','D','...']

现在,仅当列表中有非None值时才更改None值。^如果a_list中的任何值不是None,{}将返回true。你知道吗

a = ['A','B',None,'C','D',None]
b = [None,None,None,None,None,None]
a = [y if y else '...' for y in a] if any(a) else [y for y in a]
b = [y if y else '...' for y in b] if any(b) else [y for y in b]
# a changed as above, b unchanged

最后将其打包,使其在列表中的每个列表上工作:

output = [[y if y else '...' for y in x] if any(x) else [y for y in x] for x in tab1]

相关问题 更多 >

    热门问题