代码之家  ›  专栏  ›  技术社区  ›  kumar

两个元组作为python列表中的一个元素

  •  1
  • kumar  · 技术社区  · 8 年前

    我现在已经习惯了python列表。但我遇到了一个复杂的列表,我很难解析它。

    prediction=[('__label__inflation_today', 0.8),('__label__economic_outlook', 0.2)]
    

    我试图用一种更好的方式来表达这个预测,比如excel。

    predicted label              probability
    Inflation_today              0.8
    Economic_outlook             0.2
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Sruthi    8 年前

    你可以试试

    for x in prediction:
       string=x[0].replace('__label__','')
       print(string,":",x[1])
    
    inflation_today : 0.8
    economic_outlook : 0.2
    

    如果要使用这些名称访问它,还可以创建字典

    d={}
    for x in prediction:
       string=x[0].replace('__label__','')
       d[string]=x[1]
    
    d
    {'economic_outlook': 0.2, 'inflation_today': 0.8}
    
    d['economic_outlook']
    0.2
    
        2
  •  1
  •   jezrael    8 年前

    一种可能的解决方案是 pandas DataFrame , 然后使用 Series.str.replace

    import pandas as pd
    prediction=[('__label__inflation_today', 0.8), ('__label__economic_outlook', 0.2)] 
    df = pd.DataFrame(prediction, columns=['predicted label',' probability'])
    
    df['predicted label'] = df['predicted label'].str.replace('__label__', '')
    
    print (df)
        predicted label   probability
    0   inflation_today           0.8
    1  economic_outlook           0.2
    

    如果只需要数据使用 DataFrame.to_string :

    print (df.to_string(index=False, header=None))
    inflation_today  0.8
    economic_outlook  0.2