是列表和列表 总计是一个空列表
u = [ y[i][::2] for i in range(x) ]
t = [ y[i][1::2] for i in range(x) ]
for a in range(x):
for i in range(7):
Total.append(u[a][i]+t[a][i])
例如
y = [[1,3,6,9,2,1],[3,8,1,5,6,2]]
u=[[3,9,1],[8,5,2]]
t=[[1,6,2],[3,1,6]]
Total = [[4,15,3],[11,6,8]]
有更简单的方法以更Pythonic的方式编写此代码,还是最简单的方法?
答案 0 :(得分:0)
如果您的阵列长度相同,那么您可以使用它:
让你成为名单
a=[]
for i in u:
a.append(u[i]+t[i])
答案 1 :(得分:0)
您发布的语法在几个语法和语义方面都失败了。 简化到这个?
>>> [[y[i][j] + y[i][j+1] // sum of each even index with the next one
for j in range(0, len(y[i]), 2) ]
for i in range(len(y)) ]
[[4, 15, 3], [11, 6, 8]]
答案 2 :(得分:0)
我可能会使用嵌套列表理解。
y = [[1,3,6,9,2,1],[3,8,1,5,6,2]]
Total = [[i+j
for i,j in zip(sublist[0::2], sublist[1::2])]
for sublist in y]
assert Total == [[4,15,3],[11,6,8]]
for sublist in y
- 对于原始列表中的每个子列表,必须单独进行求和操作。sublist[0::2]
- 所有偶数索引值。sublist[1::2]
- 所有奇数索引值。zip(sublist[0::2], sublist[1::2])
- 一个元组(第一个,第二个),然后一个元组(第三个,第四个),等等。i+j for i,j in zip(...)
- 添加每对。答案 3 :(得分:0)
刚看到您提供了示例数据,因此请更新y
。然后我提供了一种方法来产生与你相同的结果。
您不需要循环两次以获取奇数/偶数元素的子列表,然后将它们相加。
只需使用y[index]
循环range(half of len(y[index])
,然后sum([row[index*2], row[index*2+1]])
。
total = []
y = [[1,3,6,9,2,1],[3,8,1,5,6,2]]
x = len(y)
u = [ y[i][::2] for i in range(x) ]
t = [ y[i][1::2] for i in range(x) ]
for a in range(x):
for i in range(3):
total.append(u[a][i]+t[a][i])
#the result of your method
print('yours', total)
#below is mine:
result = list(map(lambda row: [sum([row[index], row[index+1]]) for index in range(0, len(row), 2)] , y))
print('mine',result)
print('mine', result[0]+result[1])
输出:
yours [4, 15, 3, 11, 6, 8]
mine [[4, 15, 3], [11, 6, 8]]
mine [4, 15, 3, 11, 6, 8]
[Finished in 0.163s]
答案 4 :(得分:0)
我建议你使用numpy
。
import numpy as np
y = [[1,3,6,9,2,1],[3,8,1,5,6,2]]
A = np.array(y)
res = A[:, ::2] + A[:, 1::2]
# [[ 4 15 3]
# [11 6 8]]