【问题标题】:Error in Python when dealing with lists read from a text file处理从文本文件读取的列表时 Python 中的错误
【发布时间】:2017-07-05 11:21:44
【问题描述】:

这是我的代码。我是 Python 的新手:

    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"

我收到此错误:

enter image description here

【问题讨论】:

  • 你能给我们看看你的dt2.txt的样本吗?
  • 1) 您的代码没有正确缩进。 2)您应该发布错误消息,而不是它的屏幕截图。 3)“尽快”?
  • 12300110031.0 ABHIPSA Kundu的HU181 XC181 CS291 ME291 CS391 CS392 CS393 M401 HU481 CS492 CS493 CS503 CS591 CS592 CS594B CS594D CS691 CS692 CS681 12300110071.0 ABHISHEK SINGH HU181 XC181 CS391 CS392 CS493 CS592 CS593 CS681 HU781 CS792 CS891 CS892 ES191 CS291 PH291 ES291 ME291 CS393 HU481 MCS491 CS491 CS492 CS591 CS691 CS692 CS693 12300110049.0 ADITI BHAUMIK XC181 ES291 CS392 CS393 HU481 CS491 CS492 CS493 CS592 CS593 CS691 CS692 CS693 CS681 CS795A CS7
  • 首先,不要做open('filename.txt', 'r').read().split('\n'),只做open('filename.txt').readlines()。而这里的错误是它认为f 是一个整数。
  • @NickChapman:我尝试使用 a=str(f[i]).split('\t'),但我得到了同样的错误

标签: python list split


【解决方案1】:

让我们看看我是否可以提供帮助...在 python 中,csv-library 和 with ... open 被认为更“pythonic”。 with ... open 确保文件在打开后正确关闭。

import csv
with open('dt2.txt') as f:
    mydata = [i for i in csv.reader(f, delimiter='\t')] # one-liner

另一个提示...您还可以通过编写来显着缩短代码:

if str(a[j]) in ["HU101","HU301",...,"HU801B"]:
   c+=1

【讨论】:

    【解决方案2】:

    坦率地说,这段代码很糟糕。如果我正确理解您要达到的目标,这是一种更简洁的方法:

    f = open('dt2.txt','r') 
    for line in f:
        a = line.split('\t')
        print "{} with roll no: {} ".format(a[1],a[0]),
        c = sum(1 for j in a if j in set("HU101", "HU301", "HU481", "HU501", "HU601", "HU781", "HU801A", "HU801B"))
        d = 1 if "M101" in a else 0
        if c>d:
            print "is good in Soft Skills"
        else:
            print "is good in Quantitative & Logical Ability"
    f.close()
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 2017-11-09
      • 1970-01-01
      • 2014-05-26
      • 2013-12-18
      • 2021-11-10
      相关资源
      最近更新 更多