用Python将一个列表的元素替换为另一个列表的元素。

huangapple go评论144阅读模式
英文:

Replacing elements of one list with another list in Python

问题

I have two lists J1, J2 containing lists. I want to replace and insert elements of J2 into J1. But I am getting an error. I present the expected output.

import numpy as np

J1 = [[0, 0, 0, 0, 0, 9, 0]]

J2 = [[1, 4]]
for i in range(0, len(J2)):
    J = [J2[i][j] for j in J1]
    print(J)

The error is

in <listcomp>
    J = [J2[i][j] for j in J1]

TypeError: list indices must be integers or slices, not list

The expected output is

[[1, 4, 0, 0, 0, 9, 0]]
英文:

I have two lists J1,J2 containing lists. I want to replace and insert elements of J2 into J1. But I am getting an error. I present the expected output.

import numpy as np

J1=[[0, 0, 0, 0, 0, 9, 0]]

J2=[[1,4]]
for i in range(0,len(J2)):
    J=[J2[i][j] for j in J1]
    print(J)

The error is

in <listcomp>
    J=[J2[i][j] for j in J1]

TypeError: list indices must be integers or slices, not list

The expected output is

[[1, 4, 0, 0, 0, 9, 0]]

答案1

得分: 1

The error was caused by the fact that, in your code, j is an element of J1, more specifically, the first time, j = [0, 0, 0, 0, 0, 9, 0]. This is indeed a list, and not an integer or a slice, as requested by J2[i][j].

This should work, in your case where J2 is shorter than J1:

J1=[[0, 0, 0, 0, 0, 9, 0]]

J2=[[1,4]]
for i in range(0,len(J2[0])):
    J1[0][i] += J2[0][j]

print(J1)

For a more general approach:

J1 = [[1, 4]]
J2 = [[0, 0, 0, 9]]

index = 0
J = [[]]
if __name__ == "main":
    while index < len(J1[0]) and index < len(J2[0]):
        J[0].append(J1[0][index] + J2[0][index])
        index += 1
        if index == len(J1[0]):
            J[0].extend(J2[0][index:])
        elif index == len(J2[0]):
            J[0].extend(J1[0][index:])

    print(J)
英文:

The error was caused by the fact that, in your code, j is an element of J1, more specifically, the first time, j = [0, 0, 0, 0, 0, 9, 0]. This is indeed a list, and not an integer or a slice, as requested by J2[i][j].

This should work, in your case where J2 is shorter than J1:

J1=[[0, 0, 0, 0, 0, 9, 0]]

J2=[[1,4]]
for i in range(0,len(J2[0])):
    J1[0][i] += J2[0][j]

print(J1)

For a more general approach:

J1 = [[1, 4]]
J2 = [[0, 0, 0, 9]]

index = 0
J = [[]]
if __name__ == &quot;__main__&quot;:
    while index &lt; len(J1[0]) and index &lt; len(J2[0]):
        J[0].append(J1[0][index] + J2[0][index])
        index += 1
        if index == len(J1[0]):
            J[0].extend(J2[0][index:])
        elif index == len(J2[0]):
            J[0].extend(J1[0][index:])

    print(J)

答案2

得分: 0

如果你想要解压每个元素而不是从索引调用列表元素,你可以使用itertools中的zip_longestzip_longest函数将对最长的列表进行压缩,并在最后一个元素被解压后为较短的列表填充空值。Python标准库中的zip函数会在最短长度的列表处停止。

此外,我们可以实现递归,以便处理任何维度的列表。

from itertools import zip_longest

J1=[[0, 0, 0, 0, 0, 9, 0]]
J2=[[1,4]]

def replace_list(J1,J2):
    j = []
    for j1,j2 in zip_longest(J1, J2, fillvalue=[]):
        if not isinstance(j1,int) and not isinstance(j2,int): # 当J2和J1都是内部列表时
            j.append(replace_list(j1,j2))
        elif not j2: # 当J2比J1短时
            j.append(j1)
        else:
            j.append(j2)
    return j

J = replace_list(J1,J2)
print(J) # [[1, 4, 0, 0, 0, 9, 0]]

# 这也可以处理多维度的不均匀列表。
J1=[
    [0, 0, 0, 0, 0, 9, 0],
    [1, 2, 3, 4, 0, 0, 0, 1]
    ]
J2=[
    [1,4],
    [9, 8, 7, 6],
    [1, 1, 1, 1, 1, 1, 1]
    ]
    
J = replace_list(J1,J2)
print(J) # [[1, 4, 0, 0, 0, 9, 0], [9, 8, 7, 6, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1]]
英文:

If you want to unpack each element instead of calling the list element from the index, you can use zip_longest from itertools. The function zip_longest will zip to the longest list, and fill in null values for the shorter list once the last element has been unpacked. The zip function from python standard library stops at the shortest length list.

Also, we can implement recursion, so that it can handle any dimension of lists.

from itertools import zip_longest

J1=[[0, 0, 0, 0, 0, 9, 0]]
J2=[[1,4]]

def replace_list(J1,J2):
    j = []
    for j1,j2 in zip_longest(J1, J2, fillvalue=[]):
        if not isinstance(j1,int) and not isinstance(j2,int): # When J2 and J1 are a inner list
            j.append(replace_list(j1,j2))
        elif not j2: # When J2 is shorter than J1 
            j.append(j1)
        else:
            j.append(j2)
    return j

J = replace_list(J1,J2)
print(J) # [[1, 4, 0, 0, 0, 9, 0]]

# This can handle uneven lists in multiple dimensions as well.
J1=[
    [0, 0, 0, 0, 0, 9, 0],
    [1, 2, 3, 4, 0, 0, 0, 1]
    ]
J2=[
    [1,4],
    [9, 8, 7, 6],
    [1, 1, 1, 1, 1, 1, 1]
    ]
    
J = replace_list(J1,J2)
print(J) # [[1, 4, 0, 0, 0, 9, 0], [9, 8, 7, 6, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1]]

huangapple
  • 本文由 发表于 2023年3月9日 21:50:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定