有条件地用两个列表替换项目

时间:2014-05-28 06:15:43

标签: python list loops

我正在尝试将列表A中的任何“ - ”实例替换为同一索引中列表B中的元素。现在我的输出根本没有修改列表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"]] ] 

非常感谢你们给我的任何指导!

4 个答案:

答案 0 :(得分:1)

为了执行这样复杂的操作,我们可以将其分解为更简单的操作。在最简单的级别,我们想要用另一个字符串替换短划线( - ):

>>> 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']]]

答案 1 :(得分:0)

是的,for循环只会将zip()创建的列表中的分配到变量onetwo

相反,你可以这样做:

for sublist in A:
    for index, value in enumerate(sublist[1]):
        if value == '-':
            sublist[1][index] = B[index]

这应该有效,因为列表是通过引用传递的,因此外部sublist循环分配的for仍将引用与A引用的列表相同的列表。 / p>

答案 2 :(得分:0)

您需要压缩整个列表,然后在循环内进行解除引用。

for a, b in zip(A, B):
    a[1] = [B[i] if v == '-' else v for i, v in enumerate(a[1])]

答案 3 :(得分:0)

这有助于改善现有代码

A = [ ["dog", ["corgi",'-',"labrador"]], ["cat", ["tabby","persian",'-']] ]
B = ["BLANK 1","BLANK 2","BLANK 3"]

i = 0
while i < 2:
    for ele in A[i][1]:
        if ele == '-':
            dashindex = A[i][1].index(ele)
            A[i][1][dashindex] = B[dashindex]
    i = i+1;
print(A)

输出:

  

[['dog',['corgi','BLANK 2','labrador']],['cat',['tabby','persian','BLANK 3']]