【问题标题】:How do i select an item from readlines lists in Python?如何从 Python 中的 readlines 列表中选择一个项目?
【发布时间】:2020-05-10 02:17:28
【问题描述】:

这就是我目前为止的课程项目

import os 

UserSelection = input("Select a txt file: ")

with open(UserSelection, 'r', encoding= "latin-1") as f:
    lines= f.readlines()


    print("These are your headers:", lines[0])

state = words()[6]

for i in range(1,len(lines)):
    words=line.split
       if(words()[6] == 'California'):
        print(lines)

我有一个大的人口普查表,我试图只保留 STATE(即第 6 个索引)为 CA 的行。 我想 words()[6] 会这样做,但不是。 提前谢谢!

【问题讨论】:

  • 应该是words=lines[i].split(),它按空格分割并提供单词列表。您实际上可能想要使用 words=lines[i].rstrip().split() 删除每行末尾的回车符。索引 6 则为 words[6]

标签: python python-3.x list readlines


【解决方案1】:

欢迎来到 SO。在您发布的代码中,有几行不太清楚。
1) print("These are your headers:", lines[0]) 没有正确缩进。
2) state = words()[6] 在此行之前未定义单词。
3) for i in range(1,len(lines)): 在这一行中,您正在迭代行索引而没有第一行可以替换为line in lines[1>]:
4) words=line.split list 中的 split 方法在 python 中是可调用的,所以在使用该方法时应该使用 ()。
5)if(words()[6] == 'California'): 不像拆分词是一个变量而不是一个方法,所以它不应该用 () 来调用。
我理解的代码应该是代码的方式更像

import os 

userSelection = input("Select a txt file: ")

with open(userSelection ,'r', encoding= "latin-1") as f:
    lines= f.readlines()

print("These are your headers:", lines[0])

for line in lines[1:]:
    words=line.split()
    if words[6] == 'California':
        print(lines)

【讨论】:

    【解决方案2】:

    确实有效。您的错误是缩进。此外,您还有其他一些小错误。

    . . .
    
    for i in range(1,len(lines)):
      words=line.split()
      if (words[6] == 'California'):
        print(lines)
    

    .split() 是一个函数,应该作为一个函数调用。

    也不需要不必要的缩进。 用旧的 for 循环替换上面的代码 sn-p 就可以了。

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多