根据第一个列表元组值删除两个列表中的相同索引元素

时间:2018-07-25 16:05:41

标签: python python-3.x

如果我有两个如下的Python列表:

indices_tuple_list = [(1,1),(1,2),(3,1)]
values_list = ['a','b','c']

我想在两个列表中基于给定值删除相同的索引。 此值表示indices_tuple_list元组中的第二个元素。 因此,如果匹配,则必须删除元组和values_list中的相应元素。

示例:

给出值1:

结果列表:

indices_tuple_list = [(1,2)]
values_list = ['b']

给出值2:

结果列表:

indices_tuple_list = [(1,1),(3,1)]
values_list = ['a','c']

4 个答案:

答案 0 :(得分:1)

使用zip和列表理解。

remove_val = 2
result = [i for i in zip(indices_tuple_list, values_list) if i[0][1] != remove_val]
result
[((1, 1), 'a'), ((3, 1), 'c')]

new_indices, new_values = map(list, zip(*result))

输出

new_indices
[(1, 1), (3, 1)]
new_values
['a', 'c']

答案 1 :(得分:0)

to_remove = 1

indices_tuple_list = [(1,1),(1,2),(3,1)]
values_list = ['a','b','c']

new_indices_tuple_list = [v for v in indices_tuple_list if v[1] != to_remove]
new_value_list = [v for i, v in enumerate(values_list) if indices_tuple_list[i][1] != to_remove]

print(new_indices_tuple_list)
print(new_value_list)

打印:

[(1, 2)]
['b']

对于to_remove = 2,输出为:

[(1, 1), (3, 1)]
['a', 'c']

答案 2 :(得分:0)

def remove(value):
    for index, tuple in enumerate(indices_tuple_list):
        if tuple[1] == value:
            indices_tuple_list.pop(index)
            values_list.pop(index)

答案 3 :(得分:0)

使用zip

indices_tuple_list = [(1,1),(1,2),(3,1)]
values_list = ['a','b','c']

remov = 1
new_indices, new_values = [], []

for x, y in zip(indices_tuple_list, values_list):
    if x[1] == remov:
        continue
    new_indices.append(x)
    new_values.append(y)

print(new_indices)
print(new_values)

# [(1, 2)]
# ['b']
相关问题