在Python中删除不同数组的相应元素

问题描述 投票:-1回答:1

在Python 3.7中,一旦根据某些条件从数组中删除了元素,是否可以从另一个数组中删除具有与从第一个元素中删除的索引相同的索引的元素?

python
1个回答
0
投票

是的,您可以通过保留元素的索引来实现。您可以使用枚举获取索引。

list1 = list('ABCDEF')
list2 = list('abcdef')
for i, val in enumerate(list1):
    # some random condtion
    if val == 'C':
        del list1[i]
        del list2[i]

print list1 //['A', 'B', 'D', 'E', 'F']
print list2 //['a', 'b', 'd', 'e', 'f']

0
投票

以下代码从数组a1中删除元素,然后删除数组a2中具有相同索引的元素。

import array

# we will delete all values strictly greater than 10

a1 = array.array('d', [1, 34, 8, 19, 6, 27, 9])
a2 = [
    "apple",        # KEEP
    "banana",       # delete
    "kiwi",         # KEEP
    "grape",        # delete
    "strawberry",   # KEEP
    "boysenberry",  # delete
    "jackfruit"     # KEEP
]
a1_pruned = list()
a2_pruned = list()

deleted_idxs = list()

for idx in range(len(a1)):
    if a1[idx] > 10:
        a1_pruned.append(a1[idx])
        deleted_idxs.append(idx)

for idx in range(len(a2)):
    if idx not in deleted_idxs:
        a2_pruned.append(a2[idx])

print(a2_pruned)
# ['apple', 'kiwi', 'strawberry', 'jackfruit']
© www.soinside.com 2019 - 2024. All rights reserved.