我不确定我是否能说清楚,但会尝试.
我在python中有一个元组,我按如下方式进行操作(参见下面的代码).通过它,我维持一个计数器(让我们称之为'n')和'pop'项目满足一定条件.
当然,当我弹出第一个项目时,编号都出错了,我怎样才能更好地完成我想做的事情,同时只删除元组中的某些条目?
for x in tupleX:
n=0
if (condition):
tupleX.pop(n)
n=n+1
Run Code Online (Sandbox Code Playgroud)
Sin*_*ion 46
至于DSM提到,tuple的是不可改变的,但即使名单,更优雅的解决方案是使用filter:
tupleX = filter(str.isdigit, tupleX)
Run Code Online (Sandbox Code Playgroud)
或者,如果condition不是函数,请使用理解:
tupleX = [x for x in tupleX if x > 5]
Run Code Online (Sandbox Code Playgroud)
如果你真的需要tupleX作为元组,请使用生成器表达式并将其传递给tuple:
tupleX = tuple(x for x in tupleX if condition)
Run Code Online (Sandbox Code Playgroud)
在Python 3中,这不再是问题,并且您真的不想使用列表理解、强制、过滤器、函数或 lambda 来完成类似的事情。
只需使用
popped = unpopped[:-1]
Run Code Online (Sandbox Code Playgroud)
请记住,它是不可变的,因此如果您希望更改该值,则必须重新分配该值
my_tuple = my_tuple[:-1]
Run Code Online (Sandbox Code Playgroud)
例子
>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)
Run Code Online (Sandbox Code Playgroud)
如果你想要弹出的值,
>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
>>> foo, bit = foo[:-1], foo[-1]
>>> bit
1
>>> foo
(3, 5, 2, 4, 78, 2)
Run Code Online (Sandbox Code Playgroud)
或者,从后面开始处理元组的每个值......
foo = 3,5,2,4,78,2,1
for f in reversed(foo):
print(f) # 1; 2; 78; ...
Run Code Online (Sandbox Code Playgroud)
或者,随着计数...
foo = 3,5,2,4,78,2,1
for f, i in enumerate(reversed(foo)):
print(i, f) # 0 1; 1 2; 2 78; ...
Run Code Online (Sandbox Code Playgroud)
或者,强制进入一个列表..
bar = [*foo]
#or
bar = list(foo)
Run Code Online (Sandbox Code Playgroud)
是的,我们可以做到。首先将元组转换为列表,然后删除列表中的元素,然后再次转换回元组。
演示:
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)
Run Code Online (Sandbox Code Playgroud)
谢谢
好吧,我想出了一个粗略的方法。
当列表中满足条件时,我将“n”值存储在 for 循环中(我们称之为 delList),然后执行以下操作:
for ii in sorted(delList, reverse=True):
tupleX.pop(ii)
Run Code Online (Sandbox Code Playgroud)
也欢迎任何其他建议。