如果两个列表中给定的索引值都等于0,我试图从两个列表中删除索引。下面我已经编码了一种方法,但是我的实际数据集包括> 11K列表和每个列表> 30K索引。所以我的问题是,是否有人会更容易/更有效地做到这一点?
谢谢!
data = [[8,0,3,0,1,0,1],[1,0,2,8,0,0,3]]
# taking the sum of indices across all arrays if it equals 0 you know that that index is 0 across all arrays
sum_dict = {}
for array in data:
for i in range(len(array)):
value = array[i]
if i not in sum_dict:
sum_dict[i] = value
else:
sum_dict[i] += value
# removing indices that have sum=0 in all arrays and create "clean" data
clean_data = []
sum_dict = {key:val for key, val in sum_dict.items() if val == 0}
for array in data:
for i in sorted(list(sum_dict.keys()), reverse=True):
del array[i]
clean_data.append(array)
print(clean_data)
输出:
[[8, 3, 0, 1, 1], [1, 2, 8, 0, 3]]
您可以一起遍历两个列表,并且仅当它们都不等于0时才考虑元素
data = [[8,0,3,0,1,0,1],[1,0,2,8,0,0,3]]
result = []
for i, j in zip(*data):
# Only consider the elements if both i and j are not equal to 0
if not (i == j and i == 0):
result.append((i, j))
result = [list(data) for data in zip(*result)]
print(result)
输出为
[[8, 3, 0, 1, 1], [1, 2, 8, 0, 3]]