gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:13:42 25 4
gpt4 key购买 nike

在下面的列表中:

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',
...

最佳答案

使用嵌套列表推导式并且仅在列表中存在非 None 值时才替换值:

output = [[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,any(a_list) 将返回 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]

关于python - 替换子列表中的项目而不展平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com