在Python中删除具有相同索引的两个列表的元素

时间:2018-08-28 13:14:43

标签: python

我有两个大小相同的列表pp2,还有第三个列表s。 我想删除与p2中存在的p元素具有相同索引位置的s元素:

一个示例将有助于理解:

p = ['a','b','c','d','e']
p2 = [11,12,13,14,15]
s = ['a','d']
p2 = [i in p2 for i in p if i not in s]
print p2

# output of this: [False, False, False]
# wanted output: [12,13,15]

我该怎么做?

4 个答案:

答案 0 :(得分:3)

s转换为set,以有效检查其中是否包含某项,然后执行以下操作:

p = ['a','b','c','d','e','f','g','h','i','j']
p2 = [11,12,13,14,15,16,17,18,19,20]
s = set(['a','d','h','i'])

[num for num, letter in zip(p2, p) if letter not in s ]
# [12, 13, 15, 16, 17, 20]

答案 1 :(得分:1)

尝试一下,享受吧!

p = ['a','b','c','d','e','f','g','h','i','j']
p2 = [11,12,13,14,15,16,17,18,19,20]
s = ['a','d','h','i']
p2 = [j for i,j in zip(p,p2) if i not in s]
print p2

编辑:

在撰写上述解决方案时,没有提到重复的条件。针对该条件的多个答案已经发布。下面是我的版本。
-谢谢

p = ['a','b','c','d','e','f','g','h','i','j']
p2 = [11,12,13,14,15,16,17,18,19,20]
s = ['a','d','h','i']
p2 = [j for i,j in zip(p,p2) if i not in set(s)]
print p2

答案 2 :(得分:0)

  

我看到我参加聚会有点晚了,但这是我的两个例子

#looking for match and printing index number
number = 0
for char in p:
    if char in s:
        print('found match at index: %d with: %s' %(number,char))
        number += 1
    else:
        print('index: %d did not match' %(number))
        number += 1
#printing if its not a match the desired output you wanted
number2 = 0    
for char in p:
    try:
        if char in s:
            number2 += 1
        else:
            print(p2[number2])
            number2 += 1
    except IndexError:
        print('end of list')
        break

答案 3 :(得分:0)

Python具有indexpop功能,因此您需要使用它。

In [42]: p = ['a','b','c','d','e','f','g','h','i','j']

In [43]: p2 = [11,12,13,14,15]

In [44]: s = ['a','d']

In [45]: index_list = [p.index(i) for i in s]

In [46]: output = [p2.pop(index) for index in index_list]

In [47]: output
Out[47]: [11, 15]