【问题标题】:Using append to get data from a nested list使用 append 从嵌套列表中获取数据
【发布时间】:2017-11-14 17:23:18
【问题描述】:

目前我的代码是这样的:

.append("Last Name {}, First Name {} Stats: {}".format(result["L_Name"], result["F_Name"], result["Stats"]))

此代码有效,但输出与我希望代码显示的不完全相同。

问题在于 Stats 有另一个列表

  • L_Name: Doe
  • F_Name:约翰
  • 贡献:
    • 价值
    • 退货

有没有办法仅通过在我的追加中添加或更改某些内容来从 Stats 中仅挑选出 Value? 具体在这部分?

, result["Stats"]))

【问题讨论】:

  • 你能把列表和字典贴出来,或者一个样本。
  • 正如我所见,您正在尝试获取字符串格式,如果是这样,您可以尝试附加 str(result["Stats"]) 而不是 result["Stats"]

标签: python html json append


【解决方案1】:

谢谢大家,我能从你的回答中得到提示

result["Stats"]["Contribution"][1]

对我来说效果很好

【讨论】:

    【解决方案2】:

    以后请考虑仅发布工作代码,以便我们重现您的问题。我将假设result['stats'] 是一个字典,项目符号列表是键:值对。

    您可以访问您的result["Stats"] 字典中的"Contribution" 键,从而生成列表。然后,您可以使用[1] 分割列表的第二个元素。

    _.append("Last Name {}, First Name {} Stats: {}".format(
             result["L_Name"], 
             result["F_Name"],
             result["Stats"]["Contribution"][1]))
    

    这假设 result['stats'] 看起来像:

    result['stats'] = {
        'L_Name': 'Doe',
        'F_Name': 'John',
        'Contribution': [Month, Value, Returns]}
    

    【讨论】:

      【解决方案3】:

      请注意,您可以在格式字符串本身中访问 JSON 结构的项目。如果格式字符串非常复杂,这比使用位置参数更清楚。此外,您可以将整个字典传递给format_map

      l.append("Last Name {L_Name}, First Name {F_Name} Stats: {Stats[Value]}"
               .format_map(result))
      

      (在 Python 2 中,format_map 不存在,请改用format(**result)

      【讨论】:

        【解决方案4】:

        如果你只追求 Stats 的一个值,你可以得到某个索引处的值。假设 Value 位于索引 1 并且 Stats 是标准 Python 列表:

        , result["Stats"][1]))
        

        【讨论】:

        • 您需要迭代或映射附加部分中的所有元素
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-18
        • 2023-01-18
        • 1970-01-01
        • 2015-05-02
        • 2017-06-16
        • 2022-12-12
        • 1970-01-01
        相关资源
        最近更新 更多