【问题标题】:Python inport file with elements as int to listPython 导入文件,其中元素为 int 以列出
【发布时间】:2015-04-14 19:24:32
【问题描述】:

我想读成int,有没有pythonic的方法可以做到这一点?

f = open('p059_cipher.txt', 'rU')
holder = list((f.read().replace('"', '').split(',')))

Letters = list() 

for number in holder:
    Letters.append(int(number))

【问题讨论】:

  • 输入是什么样的?

标签: python list import


【解决方案1】:

我试图从您的输入中猜测,但这可能有效:

from ast import literal_eval

with open('p059_cipher.txt') as f:
    data = "[" + f.read() + "]"

result = list(map(int, literal_eval(data)))
# The call to list is only necessary if both
#   1. You explicitly need a LIST
#   2. You're running Python3
# If you're in Python2 or you just need to iterate, ignore the list call

这应该接受如下输入:

"1", "2", "3", "4", "12", "1003981890213"

并创建

result == [1, 2, 3, 4, 12, 1003981890213]

【讨论】:

    【解决方案2】:

    尝试以下方法:

    with open('p059_cipher.txt', 'rU') as f:
        numbers = list(map(int, f.read().replace('"','').split(',')))
    

    这会将包含1,2,"3" 的文件转换为[1, 2, 3](并将其保存为numbers)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多