在Python中添加列表元素

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

Adding list elements in Python

问题

我有列表 DE。我正在将 E 的元素添加到 D 的每个元素上。我呈现当前和预期的输出。

D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)):
    for j in range(0,len(E)):
        F=D[i]+E[j]
        G.append(F)
print(G)

当前的输出是

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

预期的输出是

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

I have lists D and E. I am adding element of E to each element of D. I present the current and expected outputs.

D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)): 
    for j in range(0,len(E)): 
        F=D[i]+E[j]
        G.append(F) 
print(G)

The current output is

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

The expected output is

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

答案1

得分: 1

D = [[0], [1]]
E = [[4]]
G = []
for item in D:
    for item_ in E:
        F = [item[0], item[0] + item_[0]]
        G.append(F)
print(G)

或者使用itertools:

import itertools
D = [[0], [1]]
E = [[4]]
G = []
for item, item_ in itertools.product(D, E):
    F = [item[0], item[0] + item_[0]]
    G.append(F)
print(G)
英文:
D=[[0],[1]]
E=[[4]]
G = []
for item in D:
    for item_ in E:
        F = [item[0], item[0] + item_[0]]
        G.append(F)
print(G)

or by using itertools:

import itertools
D=[[0],[1]]
E=[[4]]
G=[]
for item, item_ in itertools.product(D, E):
    F = [item[0], item[0] + item_[0]]
    G.append(F)
print(G)

答案2

得分: 0

这段代码如下:

D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)):
    for j in range(0,len(E)):
        F=[D[i][0], D[i][0]+E[j][0]]
        G.append(F)
print(G)

这段代码运行正常。

英文:

This works.

D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)): 
    for j in range(0,len(E)): 
        F=[D[i][0], D[i][0]+E[j][0]]
        G.append(F) 
print(G)

答案3

得分: 0

这会生成一个包含D和E元素之间所有可能组合的列表。代码使用列表D和E的长度来确定迭代次数,因此可以处理任意长度的列表而无需修改代码。

英文:

my approach for even longer lists:

   D=[[0],[1]]
   E=[[4],[5]]
   G=[]
   for i in range(len(D)): 
       for j in E:
           for a in j:
               G.append(D[i]+[a+i])
    print(G)

This results in a list of all possible combinations between the elements of D and E. The code uses the length of the lists D and E to determine the number of iterations, so it can handle lists of any length without needing to modify the code.

huangapple
  • 本文由 发表于 2023年2月24日 16:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554332.html
匿名

发表评论

匿名网友

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

确定