从Python元组中删除/删除项目

2024-05-17 11:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定我是否能说清楚,但我会努力的。

我在python中有一个元组,我将按如下方式进行处理(参见下面的代码)。在检查过程中,我维护了一个计数器(我们称之为“n”)和满足特定条件的“pop”项。

当然,一旦我弹出第一个项目,编号都出错了,我如何才能做我想做的更优雅,而只删除某些项目的元组飞行?

for x in tupleX:
  n=0
  if (condition):
     tupleX.pop(n)
  n=n+1

Tags: 项目代码inforif过程方式计数器
3条回答

好吧,我想出了一个粗制滥造的办法。

当列表中的条件满足时,我将“n”值存储在for循环中(我们称之为delList),然后执行以下操作:

    for ii in sorted(delList, reverse=True):
    tupleX.pop(ii)

其他建议也欢迎。

是的,我们能做到。 首先将元组转换为列表,然后删除列表中的元素,然后再次转换回元组。

演示:

my_tuple = (10, 20, 30, 40, 50)

# converting the tuple to the list
my_list = list(my_tuple)
print my_list  # output: [10, 20, 30, 40, 50]

# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position

# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]

# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)


print my_tuple # output: (10, 30, 40)

谢谢

正如DSM所提到的,tuple是不可变的,但是即使对于列表,一个更优雅的解决方案是使用filter

tupleX = filter(str.isdigit, tupleX)

或者,如果condition不是一个函数,请使用理解:

tupleX = [x for x in tupleX if x > 5]

如果确实需要tupleX作为元组,请使用生成器表达式并将其传递给tuple

tupleX = tuple(x for x in tupleX if condition)

相关问题 更多 >