简体   繁体   English

在 Python 中添加数组(二维)的每个内部数组的“第 i”个元素,并使用添加作为第“i”个元素创建一个新数组

[英]Adding “i”th elements of each of the inner arrays of an array (2 dimensional) in Python and to make a new array with the addition as the “i”th element

#Python Code #Python 代码

n = 5
sprints = [2, 4, 1, 3]
s = [[0]*n for i in range(len(sprints)-1)] #array of 5*3
add_arr = [0 for i in range(n)] #array of 5

for i in range((len(sprints)-1)):
    for j in range(n):
        if sprints[i]<sprints[i+1]:
            for k in range(sprints[i]-1,sprints[i+1]):
                s[i][k] = 1
        else:
            for m in range(sprints[i+1]-1,sprints[i]):
                s[i][m] = 1
          
print(s)

Output -输出 -

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

I want to add each of the "i"th elements of the inner arrays to create a new array such that:我想添加内部数组的每个“第 i”个元素以创建一个新数组,以便:

add_arr = [[0+1+1],[1+1+1],[1+1+1],[1+1+0],[0+0+0]] = [2,3,3,2,0]

Please Help!请帮忙!

Use zip and map :使用zipmap

add_arr = list(map(sum, zip(*s)))
print(add_arr)

[2, 3, 3, 2, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一个数组的0、2、3、4个元素与另一个数组的0、2、3、4个元素匹配,并在python中从两个数组中打印出第5个元素? - How do I match 0,2,3,4 elements of one array to 0,2,3,4 elements of another array and print the 5th element from both the arrays in python? 如何找到n维numpy数组的第i个最大元素的索引? - How to find the indices of the i-th largest element of an n-dimensional numpy array? 删除axis0的第i个索引的子元素时创建平铺的多维数组? - Creating a tiled multi-dimensional array while removing the sub element of the I'th index of axis0? 替换第 i 个维度的数组 - Replacing array at i`th dimension Python将值映射到每个第i个子列表的元素 - Python map a value to each i-th sublist's element 沿N维numpy数组的每个维索引每个第n个元素 - Index every n-th element along each dimension of a N-dimensional numpy array 如何合并 arrays 的第 2 个元素 - How to merge 2 i-th element of arrays 我如何才能使二维数组的每个元素成为python中的对象? - How can i make each element of a two dimensional array an object in python? 通过第 4 维将 4 维 np.array 拆分为 3 维 np.arrays - Split 4-dimensional np.array into 3-dimensional np.arrays by 4th dimension 二维数组的第 0 个 position 中的所有元素 - Python - All elements in the 0'th position of a 2D Array - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM