用另一个列表替换所有子列表的第三个元素
Replace the third element of all sublists with another list
我有一个列表的列表,我想 replace/update 使用新列表的所有子列表的第三个元素。
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2, 3, 4]
期望的输出:
lst_new = [['a','b', 2, 3],['d','e', 3, 9],['g','h', 4, 'j']]
可以使用numpy
吗?就像:
arr1 = np.array(lst1)
arr1[:, 2] = lst2
输出:
array([['a', 'b', '2', '3'],
['d', 'e', '3', '9'],
['g', 'h', '4', 'j']], dtype='<U1')
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2,3,4]
#We make a copy so that this 'lst_new' variable does not point to lst1
lst_new = lst1.copy()
for num, lst in zip(lst2, lst_new):
lst[2] = num
#At this point, your lst_new will be changed
试试这个:
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2, 3, 4]
for x,y in zip(lst1,lst2): #loops over both lst1 and lst2
x[2] = y
输出:
[['a', 'b', 2, 3], ['d', 'e', 3, 9], ['g', 'h', 4, 'j']]
lst1 = [['a', 'b', 'c', 3], ['d', 'e', 'f', 9], ['g', 'h', 'i', 'j']]
lst2 = [2, 3, 4]
for x in range(0, len(lst2)):
lst1[x][2] = lst2[x]
print(lst1)
只是为了有另一个选择的乐趣:
map(lambda e, subls: [*subls[:2], e, *subls[3:]], lst2, lst1))
我有一个列表的列表,我想 replace/update 使用新列表的所有子列表的第三个元素。
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2, 3, 4]
期望的输出:
lst_new = [['a','b', 2, 3],['d','e', 3, 9],['g','h', 4, 'j']]
可以使用numpy
吗?就像:
arr1 = np.array(lst1)
arr1[:, 2] = lst2
输出:
array([['a', 'b', '2', '3'],
['d', 'e', '3', '9'],
['g', 'h', '4', 'j']], dtype='<U1')
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2,3,4]
#We make a copy so that this 'lst_new' variable does not point to lst1
lst_new = lst1.copy()
for num, lst in zip(lst2, lst_new):
lst[2] = num
#At this point, your lst_new will be changed
试试这个:
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2, 3, 4]
for x,y in zip(lst1,lst2): #loops over both lst1 and lst2
x[2] = y
输出:
[['a', 'b', 2, 3], ['d', 'e', 3, 9], ['g', 'h', 4, 'j']]
lst1 = [['a', 'b', 'c', 3], ['d', 'e', 'f', 9], ['g', 'h', 'i', 'j']]
lst2 = [2, 3, 4]
for x in range(0, len(lst2)):
lst1[x][2] = lst2[x]
print(lst1)
只是为了有另一个选择的乐趣:
map(lambda e, subls: [*subls[:2], e, *subls[3:]], lst2, lst1))