我有一个这样的二维列表:
list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]
我想将每一行的每个元素与另一行相加,结果是这样的:
outcome_list = [[10,13,16,20,24],[16,18,14,32,40],[10,13,20,28,34]]
我的代码是这样的:
d = len(list1)
for i in range(0, d-1):
list2 = list[i][:] + list[i+1][:]
但这不起作用。
答案 0 :(得分:1)
可以这样做:
list1 = [[2, 4, 6, 8, 9], [8, 9, 10, 12, 15], [8, 9, 4, 20, 25]]
print([[sum(l) for l in zip(list1[i], list1[(i+1) % len(list1)])]
for i in range(len(list1))])
[[10, 13, 16, 20, 24], [16, 18, 14, 32, 40], [10, 13, 10, 28, 34]]
答案 1 :(得分:0)
将zip()
与列表理解结合使用:
list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]
list1 = list1 + [list1[0]]
print([list(map(lambda x: sum(x), zip(x, y))) for x, y in zip(list1, list1[1:])])
# [[10, 13, 16, 20, 24], [16, 18, 14, 32, 40], [10, 13, 10, 28, 34]]
答案 2 :(得分:0)
尝试一下
Object.entries(obj)[0][1].thumbId
答案 3 :(得分:0)
您可以通过将列表本身压缩,但将项目向右旋转来对子列表进行配对,然后将d = len(list1)
for i in range(0, d-1):
list2 = [a + b for a,b in zip(list[i],list[i+1])]
对与列表理解中的 string[] getfilesname()
{
string folderPath = Path.Combine(Application.persistentDataPath, foldername);
string[] filePaths = Directory.GetFiles(folderPath, "*.txt");
foreach (string file in filePaths)
{
var onlyFileName = Path.GetFileNameWithoutExtension(file);
if (mylist.IndexOf(onlyFileName) == -1)
{
mylist.Add(onlyFileName);
}
Debug.Log(onlyFileName);
}
dropi.AddOptions(mylist);
return filePaths;
}
方法配对:
map
这将返回:
operator.add
答案 4 :(得分:0)
使用numpy.roll
:
In [1]: import numpy as np
In [2]: a = np.array([[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]])
In [3]: a + np.roll(a, -1, axis=0)
Out[3]:
array([[10, 13, 16, 20, 24],
[16, 18, 14, 32, 40],
[10, 13, 10, 28, 34]])
答案 5 :(得分:0)
这是使用itertools的另一种方法,该工具应适用于list1中任意数量的列表:
from itertools import combinations
list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]
outcome = [ list(map(sum,zip(*rows))) for rows in combinations(list1,2) ]