问题
I have a dictionary like this:
a= {1982: [(1,2,3,4)],
1542: [(4,5,6,7),
(4,6,5,7)]}
and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7)
to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]
I have tried
for key, value in a.items():
for i in value:
i = tuple(i)
but it does now work. How can I achieve it?
回答1:
As far as I understand you want to convert each tuple in a list. You can do this using a dictionary comprehension:
{k: [list(ti) for ti in v] for k, v in a.items()}
will give
{1542: [[4, 5, 6, 7], [4, 6, 5, 7]], 1982: [[1, 2, 3, 4]]}
Is that what you are after?
回答2:
In-place:
for key, value in a.items():
for i, t in enumerate(value):
value[i]= list(t)
New objects:
{key: [list(t) for t in value] for key, value in a.items()}
回答3:
You can use "tupleo" library
from tupleo import tupleo.
val = tupleo.tupleToList(a[1542]).
print(val) [[4,5,6,7], [4,6,5,7]]
tupleo gives you full depth level conversion of tuple to list. and it have functionality to convert tuple to dict also based on index.
来源:https://stackoverflow.com/questions/47731301/convert-tuple-to-list-in-a-dictionary