我不确定我是否能说清楚但会尝试。
我在 python 中有一个元组,我按如下方式进行(见下面的代码)。在经历它时,我维护一个计数器(我们称它为“n”)和满足特定条件的“弹出”项目。
当然,一旦我弹出第一个项目,编号就全部出错了,我怎样才能更优雅地做我想做的事情,同时只动态地删除元组的某些条目?
for x in tupleX:
n=0
if (condition):
tupleX.pop(n)
n=n+1
正如
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)
是的,我们可以做到。 首先将元组转换为列表,然后删除列表中的元素,然后再次转换回元组。
演示:
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)
谢谢
在 Python 3 中,这不再是一个问题,您真的不想为这样的事情使用列表推导、强制转换、过滤器、函数或 lambda。
只需使用
popped = unpopped[:-1]
记住它是不可变的,所以如果你想改变它就必须重新分配值
my_tuple = my_tuple[:-1]
例子
>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)
如果你想要弹出的值,,
>>> 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)
或者,从后面开始处理元组的每个值...
foo = 3,5,2,4,78,2,1
for f in reversed(foo):
print(f) # 1; 2; 78; ...
或者,用伯爵...
foo = 3,5,2,4,78,2,1
for f, i in enumerate(reversed(foo)):
print(i, f) # 0 1; 1 2; 2 78; ...
或者,强制进入列表..
bar = [*foo]
#or
bar = list(foo)
好吧,我想出了一个粗略的方法。
当列表中的条件满足时,我将“n”值存储在 for 循环中(我们称之为 delList),然后执行以下操作:
for ii in sorted(delList, reverse=True):
tupleX.pop(ii)
也欢迎任何其他建议。
也许你想要字典?
d = dict( (i,value) for i,value in enumerate(tple))
while d:
bla bla bla
del b[x]
有一个简单但实用的解决方案。
正如 DSM 所说,元组是不可变的,但我们知道列表是可变的。 因此,如果将元组更改为列表,它将是可变的。然后您可以按条件删除项目,然后再次将类型更改为元组。就是这样。
请看下面的代码:
tuplex = list(tuplex)
for x in tuplex:
if (condition):
tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)
例如,以下过程将从给定元组中删除所有偶数。
tuplex = (1, 2, 3, 4, 5, 6, 7, 8, 9)
tuplex = list(tuplex)
for x in tuplex:
if (x % 2 == 0):
tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)
如果你测试最后一个元组的类型,你会发现它是一个元组。
最后,如果你想像你那样定义一个索引计数器(即 n),你应该在循环之前初始化它,而不是在循环中。
也许更短的方法:
tup = (0, 1, 2, 3)
new_tup = (*tup[:-2], tup[-1])
print(new_tup) # (0, 1, 3)
假设您有一个以元组作为键的
dict
,例如:labels = {(1,2,0): 'label_1'}
您可以按如下方式修改元组键的元素:
formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}
在这里,我们忽略最后的元素。
一个解决方案是转换为 set 并带回元组
tupleX = (
"ZAR",
"PAL",
"SEV",
"ALC",
"LPA",
"TFN",)
remove = (
"LPA",
"TFN",)
tuple(set(tupleX) - set(remove))
('ZAR','PAL','ALC','SEV')
最好的解决方案是将元组应用于列表理解,但要提取一个 这可能有效的项目:
def pop_tuple(tuple, n):
return tuple[:n]+tuple[n+1:], tuple[n]