[英]I'm trying to convert a tuple to a list in python
I'm trying to turn this:我试图把这个:
('a','b',['a1','b1','b3',('a2',('ab','bd','cd'),'b2','c2')])
into this:进入这个:
('a','b',['a1','b1','b3',('a2',['ab','bd','cd'],'b2','c2')])
changing the ('ab', 'bd', 'cd') to ['ab', 'bd', 'cd']
将
('ab', 'bd', 'cd') to ['ab', 'bd', 'cd']
You can use the list()
function:您可以使用
list()
函数:
tup = ('ab', 'bd', 'cd')
lst = list(tup)
print(lst)
Output:输出:
['ab', 'bd', 'cd']
EDIT:编辑:
If you want to get your output, it is a bit more complicated since tuples are immutable (unchangable), so we need to create a new tuple that stores the new change:如果你想得到你的输出,它有点复杂,因为元组是不可变的(不可改变的),所以我们需要创建一个新的元组来存储新的变化:
origTup = ('a','b',['a1','b1','b3',('a2',('ab','bd','cd'),'b2','c2')])
origLst = list(origTup) #convert origTup to a list so we can edit it
partialLst = list(origLst[2][3]) #extract ('a2',('ab','bd','cd'),'b2','c2') and change it to a list
partialLst[1] = list(partialLst[1]) #change ('ab','bd','cd') to a list
partialTup = tuple(partialLst) #convert ['a2',['ab','bd','cd'],'b2','c2'] back to a tuple
origLst[2][3] = partialTup #put the tuple back into our origLst
newTup = tuple(origLst) #create a new tuple that converts our origLst to a tuple
print(newTup)
Output:输出:
('a', 'b', ['a1', 'b1', 'b3', ('a2', ['ab', 'bd', 'cd'], 'b2', 'c2')])
First, we convert origTup
to a list, origLst
so we can edit it.首先,我们将
origTup
转换为列表origLst
以便我们可以编辑它。 Then, we will extract ('a2',('ab','bd','cd'),'b2','c2')
from our list and change it to a list: ['a2',('ab','bd','cd'),'b2','c2']
然后,我们将从列表中提取
('a2',('ab','bd','cd'),'b2','c2')
并将其更改为列表: ['a2',('ab','bd','cd'),'b2','c2']
Now that we can edit it, we will change the first element, ('ab','bd','cd')
, to a list: ['ab','bd','cd']
.现在我们可以对其进行编辑,我们将把第一个元素
('ab','bd','cd')
更改为一个列表: ['ab','bd','cd']
。 Then, we will again change the outer portion into a tuple as it originally was: ['a2',['ab','bd','cd'],'b2','c2']
into ('a2',['ab','bd','cd'],'b2','c2')
然后,我们将再次将外部部分更改为原来的元组:
['a2',['ab','bd','cd'],'b2','c2']
变为('a2',['ab','bd','cd'],'b2','c2')
Finally, we set the element in our origLst
to this tuple, and then create a new tuple to store our change.最后,我们将
origLst
中的元素设置为这个元组,然后创建一个新元组来存储我们的更改。
I hope this helped!我希望这有帮助! Please let me know if you need any further help or clarification!
如果您需要任何进一步的帮助或澄清,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.