简体   繁体   English

将列表中的项目替换为 python 中另一个列表中的项目

[英]Replacing items in a list with items from another list in python

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]

list2 = [0,2,1,0,5]

Would it be possible to replace each 3 in list1 with an element from list2 ?是否可以用list2中的元素替换list1中的每个 3 If so, how would I go about doing this?如果是这样,我将如何做到这一点 go ?

You could create an iterator for list2 , and then call next() to replace the next element in list1 that is equal to 3 , while using a list comprehension.您可以为list2创建一个迭代器,然后调用next()来替换list1中等于3的下一个元素,同时使用列表理解。

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
list2 = [0,2,1,0,5]
l2 = iter(list2)

out = [i if i!=3 else next(l2) for i in list1]
print(out)

Output: Output:

[0, 4, 1, 1, 0, 2, 1, 0, 4, 1, 0, 2, 5]

We can use two pointers to keep track of list1 and list2 .我们可以使用两个指针来跟踪list1list2 Then we replace each 3 in list1 with a value from list2 even it is not 0 until traversing to the end of any of the list.然后我们用 list2 中的值替换list1中的每个 3, list2 value不是 0 ,直到遍历到任何列表的末尾。

list1 = [3, 4, 1, 1, 0, 3, 1, 0, 4, 3, 3, 2, 3]
list2 = [0, 0, 0, 0, 0]
x = 0
y = 0
while x < len(list1) and y < len(list2):
    if list1[x] == 3:
        list1[x] = list2[y]
        y += 1
    x += 1
print(list1)

Output: Output:

[0, 4, 1, 1, 0, 0, 1, 0, 4, 0, 0, 2, 0]
list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
list2 = [0,2,1,0,5]
l1_num = 3 # number to be replaced in list 1
l2_num = 0 # number to be replaced in list 2
n = min(list1.count(l1_num),list2.count(l2_num))
for i in range(n):
    list1[list1.index(l1_num)] = l2_num
    list2[list2.index(l2_num)] = l1_num
#list1 = [0, 4, 1, 1, 0, 0, 1, 0, 4, 3, 3, 2, 3]
#list2 = [3, 2, 1, 3, 5]

we can use for in and store our needed short list value out of the loop.我们可以使用for in并在循环之外存储我们需要的短列表值。 like the following code will replace all 3 in list1 with zeros and all 0 in list2 with 3s in list1:像下面的代码一样,会将list1中的所有 3 替换为零,将list2中的所有 0 替换为 list1 中的 3:

    list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
    list2 = [0,1,0,3,0]
    #shortlistval will be used to store short list desired value
    shortlistVal =1;#default val is just for declaration 
    for i1 in range(0, len(list1)):
        for i in range(0,len(list2)):
            if list1[i1] ==3 and list2[i] == 0:
                shortlistVal=list2[i]
                list2[i]=list1[i1]
        if list1[i1]==3:
            list1[i1]= shortlistVal
    print(list1)
    print(list2)

Output: Output:

   [0, 4, 1, 1, 0, 0, 1, 0, 4, 0, 0, 2, 0]
   [3, 1, 3, 3, 3]

Use two for loops and replace each 3 for 0 s in list 2.使用两个 for 循环并替换列表 2 中的每个 3 for 0 s。

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
list2 = [0,2,1,0,5]

for i in range(list2.count(0)):
    for x in list1:
        if x == 3: list1[list1.index(x)] = 0; break

print(list1)

output: output:

[0, 4, 1, 1, 0, 0, 1, 0, 4, 3, 3, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM