删除元组中的数字

时间:2014-04-13 05:29:13

标签: python

def pop_at_index(seq,index):
    if index not in range(-len(seq),len(seq)):
        return seq
    lst = []
    for i in seq:
        if i != seq[index]:
            lst.append(i)
        else:
            return seq
    return tuple(lst)

这是我的代码,它假设适用于以下情况,但它没有

print(pop_at_index((1, 2, 3), -1))#(1, 2)
print(pop_at_index((1, ), 0)) #()
print(pop_at_index((1, 3, 5, 7), 0)) #(3,5,7)
print(pop_at_index((2, 4, 6, 8, 10), -10)) #(2, 4, 6, 8, 10)
print(pop_at_index((1, 3, 5, 7), -2)) #(1,3,7)

1 个答案:

答案 0 :(得分:2)

使用del声明或list.pop

def pop_at_index(seq,index):
    lst = list(seq)
    try:
        del lst[index]
    except IndexError:
        return seq
    return tuple(lst)

>>> print(pop_at_index((1, 2, 3), -1))
(1, 2)
>>> print(pop_at_index((1, ), 0))
()
>>> print(pop_at_index((1, 3, 5, 7), 0))
(3, 5, 7)
>>> print(pop_at_index((2, 4, 6, 8, 10), -10))
(2, 4, 6, 8, 10)
>>> print(pop_at_index((1, 3, 5, 7), -2))
(1, 3, 7)

为什么你的代码不起作用?

else:
    return seq

上述语句导致函数返回seq。 (else部分将始终执行,因为序列中始终匹配的项目)