英文:
Adding list elements in Python
问题
我有列表 D
和 E
。我正在将 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论