我有這樣一個列表的列表:你如何將列表中的第一個元素乘以Python中的數字(列表中的列表)?
[[1,2,3],[4,5,6]]
我想通過10乘以各內列表的第一個元素所以預期的輸出將是這樣:
[[10,2,3],[40,5,6]]
我怎麼能這樣做?
我有這樣一個列表的列表:你如何將列表中的第一個元素乘以Python中的數字(列表中的列表)?
[[1,2,3],[4,5,6]]
我想通過10乘以各內列表的第一個元素所以預期的輸出將是這樣:
[[10,2,3],[40,5,6]]
我怎麼能這樣做?
試試這個:
my_list = [[1,2,3],[4,5,6]]
for i in my_list:
i[0] *= 10 # multiply the first element of each of the inner lists by 10
print(my_list)
輸出:
[[10, 2, 3], [40, 5, 6]]
如果您正在使用大型陣列工作,那麼numpy
作品比單獨蟒好,爲許多其他原因也是如此。
lst = [[1,2,3],[4,5,6]] # if you have your list in python
lst = np.array(lst) # simple one-liner to convert to an array
lst
Out[32]:
array([[1, 2, 3],
[4, 5, 6]])
lst[:,0] *= 10 # multiply first column only by 10. This removes the need
# for python's "for" loops, which improves performance
# on larger arrays
lst
Out[34]:
array([[10, 2, 3],
[40, 5, 6]])
謝謝,我會記住這個大的。 – 79t97g
謝謝,這個工程。 – 79t97g