【问题标题】:How do I take numbers from a file and read them as integers if they have headings in python?如果它们在python中有标题,我如何从文件中获取数字并将它们作为整数读取?
【发布时间】:2016-02-24 20:50:42
【问题描述】:

我有一个包含一堆数字的文件,但有些标题让我无法做很多事情。该文件如下所示:

x: 
1 2 3 4 

f: 
5 6 7 8

h:
9 10 11 12 13

所以我有这个程序,我相信它可以帮助我访问这些号码,但我收到了一条错误消息。

filename = input('file: ')
f = open(filename, 'r')
output=[]
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
    if i == h:
        break
    x.append(map(int,line.split()[:w]))
output.append(x)

所以我尝试对标头进行条带化,但我收到一条错误消息,指出它是一个字符串等。

filename = input('file: ')
f = open(filename, 'r')
output=[]
func = f.readline()
lines = func.strip('x').strip('f').strip('h').split()
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
    if i == h:
         break
    x.append(map(int,line.split()[:w]))
output.append(x)

有什么建议吗?

【问题讨论】:

  • 您想在尝试访问列表中的内容之前验证列表的长度。如果 x =[ ] 并且您执行 x[1] 您的应用程序将引发错误。如果 len(x) > 0: x[1]
  • 我猜你的行是一个字符串而不是一个列表 '[22 .. .']

标签: python list indexing


【解决方案1】:

例子

filename = input('filename: ')

with open(filename, 'r') as f:
    for line in f: # line one-by-one
        line = line.strip() # strip to check empty lines
        if line: # skip empty lines
            elements = line.split()
            print(elements[2]) # [column]

或

filename = input('filename: ')

# get not empty lines
lines = []

with open(filename, 'r') as f:
    for line in f: # 
        line = line.strip() # strip to check empty lines
        if line: # skip empty lines
            elements = line.split()
            lines.append(elements)

# work with lines one-by-one

for line in lines: # 
    print(line[2]) # [column]

# direct access to any element 

print(lines[1][2]) # [row][column]

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多