[英]How to change an element in a list of lists if it has a specific index and condition that is met?
I want to be able to take a list of lists (lst)
and a list of indexes and those elements in lst that have that have those indexes and also meet the condition ( == '1')
to be changed to '0'
. 我希望能够获取列表列表(lst)
和索引列表以及lst中那些具有那些索引并且还满足条件( == '1')
元素要更改为'0'
。
If I input 如果我输入
lst = [['1','2','3'],[],['4','2','1']]
and 和
specific_indexes = [(0, 0), (0, 2), (2, 0), (2, 2)]
I get [['0', '2', '3'], [], ['4', '2', '0']]
我得[['0', '2', '3'], [], ['4', '2', '0']]
but I would like faster way to do this. 但我想更快地做到这一点。
def change(lst, specific_indexes):
for (x,y) in specific_indexes:
if lst[y][x] == '1':
lst[y][x] = '0'
return lst
...but I would like faster way to do this. ...但我想更快地做到这一点。
If you are interested in performance, you can use a specialist 3rd party library such as NumPy . 如果您对性能感兴趣,可以使用NumPy等专业的第三方库。 This does mean you have to define a regular 2d array as an input, or transform it into one as shown below. 这意味着您必须将常规的2d数组定义为输入,或将其转换为1,如下所示。
import numpy as np
lst = [['1','2','3'],[],['4','2','1']]
idx = [(0, 0), (0, 2), (2, 0), (2, 2)]
# calculate column number and construct NumPy array
colnum = max(map(len, lst))
arr = np.array([sublst if sublst else ['0'] * colnum for sublst in lst]).astype(int)
idx = np.array(idx)
# calculate indexer and mask array conditionally
mask = np.ix_(idx[:, 1], idx[:, 0])
arr[mask] = np.where(arr[mask] == 1, 0, arr[mask])
print(arr)
# array([[0, 2, 3],
# [0, 0, 0],
# [4, 2, 0]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.