Python:从列表中删除特定值

时间:2013-12-08 03:21:57

标签: python list function python-2.7 python-3.x

如果是

# Displaying old and reference in columns for better visual #

old=      [2,2,6,6,2,4, 6, 6, 8,2]
reference=[7,1,6,2,4,9,10,16,12,5]
ID=2

从引用列表中删除变量ID和删除的更快方法是什么? 旧列表中的旧[引用[ID匹配]]?

我在问我的问题时碰巧开发了这个解决方案......但有更好的方法吗?

def List_Value_Removal(old,reference,ID):
    counter=0
    new=[]
    for test in reference:
        if ID!=test:
           new.append(old[counter])
        checker+=1
    return new

4 个答案:

答案 0 :(得分:5)

使用zip() function配对列表,然后使用列表理解仅保持值,其中参考值与ID不匹配:

def List_Value_Removal(old, reference, ID):
    return [v for v, ref in zip(old, reference) if ref != ID]

 values, references = List_Value_Removal(values, references, some_id)

演示:

>>> old = [2, 2, 6, 6, 2, 4, 6, 6, 8, 2]
>>> reference = [7, 1, 6, 2, 4, 9, 10, 16, 12, 5]
>>> ID = 2
>>> [v for v, ref in zip(old, reference) if ref != ID]
[2, 2, 6, 2, 4, 6, 6, 8, 2]

如果您还需要更新reference,请返回两个列表:

def List_Value_Removal(old, reference, ID):
    return zip(*((v, ref) for v, ref in zip(old, reference) if ref != ID))

演示:

>>> new, newref = zip(*((v, ref) for v, ref in zip(old, reference) if ref != ID))
>>> new
(2, 2, 6, 2, 4, 6, 6, 8, 2)
>>> newref
(7, 1, 6, 4, 9, 10, 16, 12, 5)

答案 1 :(得分:1)

你也可以这样做:

old=      [2,2,6,6,2,4,6,6,8,2]
reference=[7,1,6,2,4,9,10,16,12,5]
ID=2

new = [old[i] for i in range(len(old)) if reference[i] != ID]

答案 2 :(得分:0)

考虑到两个列表的长度相同且只有一个要删除的索引,顺便说一句,我们可以使它更通用:

>>> old = [2,2,6,6,2,4, 6, 6, 8,2]
>>> reference=[7,1,6,2,4,9,10,16,12,5]
>>> id = 2
>>> del old[(reference.index(id))]
>>> old
[2, 2, 6, 2, 4, 6, 6, 8, 2]
>>>

答案 3 :(得分:0)

def List_Value_Removal(old,ref, id):
    new = old[:]
    ind = ref.index(id)
    new.pop(ind)
    return new

不确定您是否有使用两个阵列的特殊原因? 如果您使用了词典:

ref = {7:2,1:2,6:6,2:6,4:2,9:4,10:6,16:6,12:8,5:2}

你可以:

ref.pop(id)