【发布时间】:2015-02-17 18:19:29
【问题描述】:
我创建了一个字典键,它是字符串和元组的元组。典型的键看起来像
("string1", ('string2','string3', 'string4'), (int1, int2, int3) )
我现在需要将键复制到列表中以修改 string2 和 int2 并将其重新转换回新元组,然后该元组将用作新条目的字典键。
当我尝试使用此元组制作列表时
listKey = [list(i) for i in key]
我得到的输出看起来像
[['s','t','r','i','n','g','1'],['string2','string3','string4'],[int1 , int2, int3]]
- 当我将“string1”转换为列表时,如何将其保留在原始字典键中?
- 修改后的列表转回元组时如何保留'string1'?
【问题讨论】:
-
如果
i是一个元组,你可能只需要调用list(i)。 -
你可能不应该这样做,而应该处理你的数据结构(例如
(("string1"), ('string2', 'string3', ...) ...)),但如果你确实需要,你总是可以这样做listKey = [i if isinstance(i, str) else list(i) for i in key] -
谢谢你的工作。但正如您所建议的,我会尝试将整个键设为元组的元组。
标签: python list dictionary data-structures tuples