简体   繁体   English

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

[英]Delete elements of two list with same index in python

I have two lists p & p2 with the same size, and a third list s . 我有两个大小相同的列表pp2和第三个列表s I wanna remove the elements of p2 that have the same index location with those elements of p that exist in s : 我想删除与s中存在的p元素具有相同索引位置的p2元素:

An example would help understanding: 一个例子将有助于理解:

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]

How can I do this? 我怎样才能做到这一点?

Turn s into a set for efficiently checking whether an item is in it or not, and do: 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]

Try this and enjoy! 试试这个,享受吧!

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

Edit: 编辑:

At the time of writing above solution, condition of repetitions weren't mentions. 在撰写上述解决方案时,没有提到重复的条件。 Multiple answers for that conditions is already posted. 针对该条件的多个答案已经发布。 Below is my version though. 下面是我的版本。
-Thanks -谢谢

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

I see i am a little late to the party, but here is my two examples 我看到我参加聚会有点晚了,但这是我的两个例子

#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

The Python has index and pop function, so you need to use it. 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM