为什么.readlines()生成单个字符的列表?

2024-05-01 22:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这种格式的文本文件:

EFF   3500.  GRAVITY 0.00000  SDSC GRID  [+0.0]   VTURB 2.0 KM/S    L/H 1.25                            
  wl(nm)    Inu(ergs/cm**2/s/hz/ster) for 17 mu in 1221 frequency intervals
            1.000   .900  .800  .700  .600  .500  .400  .300  .250  .200  .150  .125  .100  .075  .050  .025  .010
    9.09 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.35 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.61 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.77 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.96 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
   10.20 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
   10.38 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0

...more numbers 

我正在努力使File[0][0]打印单词“EFF”等等。在

^{pr2}$

但是,它继续输出单个字符,就好像每个列表索引都是一个字符一样。这也包括空格。我在一个循环中使用split(),因为如果我放入readlines().split(),它会给出一个错误。在

输出:

    E
    F
    F



    3
    5
    0
    0
    .


    G
    R
    A
    V
    I

...ect

我做错什么了?在


Tags: 格式cm字符gravitygridsplit文本文件nm
2条回答

你想要这样的东西:

for line in File:
    fields = line.split()
    #fields[0] is "EFF", fields[1] is "3500.", etc.

split()方法返回字符串列表,它不修改调用的对象。在

>>> text = """some
... multiline
... text
... """
>>> lines = text.splitlines()
>>> for i in range(len(lines)):
...     lines[i].split()  # split *returns* the list of tokens
...                       # it does *not* modify the string inplace
... 
['some']
['multiline']
['text']
>>> lines   #strings unchanged
['some', 'multiline', 'text']
>>> for i in range(len(lines)):
...     lines[i] = lines[i].split() # you have to modify the list
... 
>>> lines
[['some'], ['multiline'], ['text']]

如果你想要一条直线:

^{pr2}$

使用文件对象时,它应该是:

with open(z[1]) as f:  
    File = [line.split() for line in f]

顺便说一下,循环时使用的是反惯用语。如果要循环遍历iterable,只需执行以下操作:

for element in iterable:
    #...

如果还需要元素的索引,请使用enumerate

for index, element in enumerate(iterable):
    #...

在您的情况下:

for i, line in enumerate(File):
    File[i] = line.split()

for word in File[1]:
    print word

相关问题 更多 >