【问题标题】:How to convert a tuple of string and tuples into a list of string and lists如何将字符串和元组的元组转换为字符串和列表的列表
【发布时间】: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]]

  1. 当我将“string1”转换为列表时,如何将其保留在原始字典键中?
  2. 修改后的列表转回元组时如何保留'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


【解决方案1】:

您可能只需要致电list(i) 如果没有,你可以试试(("string1"),('string2', 'string3', ...) ...)

或者你可以使用这个:

listKey = [i if isinstance(i, str) else list(i) for i in key]

希望这有助于解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多