【问题标题】:how to remove brackets from an inserted tuple in a list?如何从列表中插入的元组中删除括号?
【发布时间】:2020-05-06 20:25:45
【问题描述】:

请有人帮我从我的元组列表中删除多余的括号吗?

latest_Value = {"17:00:00": 100.00}

Dict1 = {"current value": 100, "stock_purchased": "false", "Historic value": [('16:00:00', 55.50), ("15:00:00", 45.50), ("14:00:00", 75.50),("13:00:00", 65.50), ("12:00:00", 55.50)]}

# converting the latest_value into a tuple
List_it = [(k, v) for k, v in latest_Value.items()]

# insert the tuple into the tuple list
Dict1['Historic value'].insert(0, List_it)

data2 = Dict1["Historic value"]
print(data2)

#output 

[[('17:00:00', 100.0)], ('16:00:00', 55.5), ('15:00:00', 45.5), ('14:00:00', 75.5), ('13:00:00', 65.5), ('12:00:00', 55.5)]

当列表被修改时,它会添加一个嵌套列表而不仅仅是元组。 你如何避免这种情况?

亲切的问候,

安德鲁

【问题讨论】:

    标签: python list tuples brackets


    【解决方案1】:
    # converting the latest_value into a tuple
    List_it = [(k, v) for k, v in latest_Value.items()]
    

    事实上,这是错误的。这会将整个 dict 转换为元组,而不仅仅是最后一个键值对,因此 Dict1['Historic value'].insert(0, List_it) 将整个元组列表添加到 Dict1['Historic value']

    latest_Value 包含单个键值对这一事实不会改变List_it 将是一个元组列表这一事实。

    如果你改为Dict1['Historic value'].insert(0, List_it[0]),那么你会得到你想要的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多