【问题标题】:Convert text file to a dictionary of key strings and value integers将文本文件转换为键字符串和值整数的字典
【发布时间】:2019-05-24 10:53:03
【问题描述】:

我有一个这样的数字文本文件

文本文件 '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 我想把它转换成这样的数组:

myary= {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} 但我希望 keysstringvaluesinteger

我认为我能够将所有这些作为字符串获取,但这不是我想要的 我希望它是分开的

【问题讨论】:

  • 您的术语有一些严重的不一致之处。虽然您的意思总体上可能很清楚,但有时可能很难说出来

标签: python arrays file dictionary


【解决方案1】:

如果你不想使用literal_eval

str="'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9"
print({x[0].replace("'", ""):int(x[1]) for x in [y.split(': ') for y in [z for z in str.split(',')]] })
#{'2': 2, '7': 7, '8': 8, '4': 4, '1': 1, '9': 9, '3': 3, '6': 6, '5': 5}

【讨论】:

    【解决方案2】:

    使用ast.literal_eval

    import ast
    txt = "'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9"
    print (ast.literal_eval('{' + txt + '}'))
    #{'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 2017-02-11
      • 2012-03-02
      • 2012-03-26
      • 1970-01-01
      相关资源
      最近更新 更多