我试图用同一索引中列表 B 中的元素替换列表 A 中的任何“-”实例。现在我的输出根本不修改列表 A,所以我怀疑我的 for 循环正在使用副本。
A = [ ["dog", ["corgi",'-',"labrador"]], ["cat", ["tabby","persian",'-']] ]
B = ["BLANK 1","BLANK 2","BLANK 3"]
i = 0
for one,two in zip(A[i][1],B):
if one == '-':
one = two
i += 1
print(A)
我希望我的输出(即修改后的列表 A)如下所示:
[ ["dog", ["corgi","BLANK 2","labrador"]], ["cat", ["tabby","persian","BLANK 3"]] ]
非常感谢你们给我的任何指导!
最佳答案
为了执行如此复杂的操作,我们可以将其分解为更简单的操作。在最简单的层面上,我们希望用另一个字符串替换破折号 (-):
>>> x = 'corgi'
>>> y = 'BLANK 1'
>>> x if x != '-' else y
corgi
>>> x = '-'
>>> y = 'BLANK 2'
>>> x if x != '-' else y
BLANK 2
下一步是将 ["corgi",'-',"labrador"]
替换为 ["corgi",'BLANK 2',"labrador"]
:
>>> breed = ["corgi",'-',"labrador"]
>>> B = ["BLANK 1","BLANK 2","BLANK 3"]
>>> zip(breed, B)
[('corgi', 'BLANK 1'), ('-', 'BLANK 2'), ('labrador', 'BLANK 3')]
>>> [x if x != '-' else y for x, y in zip(breed, B)]
['corgi', 'BLANK 2', 'labrador']
最后,我们来看看大局:
>>> C = [ [animal,
[x if x != '-' else y for x, y in zip(breed, B)] ]
for animal, breed in A]
>>> print C
[['dog', ['corgi', 'BLANK 2', 'labrador']], ['cat', ['tabby', 'persian', 'BLANK 3']]]
关于python - 有条件地用两个列表替换项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23904076/