处理从文本文件读取的列表时,Python出错

2024-04-26 21:21:54 发布

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

这是我的密码。我是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


Tags: intxt密码forreadifisrange
2条回答

看看我能不能帮上忙。。。在python的csv库和。。。开放被认为是更“Python”。与…有关的。。。打开确保文件在打开后正确关闭。你知道吗

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

坦白说,这个代码很糟糕。如果我正确理解你想要达到的目标,这是一个更干净的方法:

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()

相关问题 更多 >