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)
好吧,我想出了一个粗制滥造的办法。
当列表中的条件满足时,我将“n”值存储在for循环中(我们称之为delList),然后执行以下操作:
其他建议也欢迎。
是的,我们能做到。 首先将元组转换为列表,然后删除列表中的元素,然后再次转换回元组。
演示:
谢谢
正如
DSM
所提到的,tuple
是不可变的,但是即使对于列表,一个更优雅的解决方案是使用filter
:或者,如果
condition
不是一个函数,请使用理解:如果确实需要tupleX作为元组,请使用生成器表达式并将其传递给
tuple
:相关问题 更多 >
编程相关推荐