Python len()不好

时间:2017-04-20 21:16:03

标签: python python-3.x

我有一个文件,我希望得到这些行的长度。

但是当我得到长度时:

  

8 10 11 9 9 30 11 12 11 10 10 8 8 26 13等......

有我的代码:

competition = []
with open('verseny.txt') as f:
    competitor_number= int(next(f))
    for line in f:
        shots = line.split()
        competition.append(str(shots))

for num,shots in enumerate(competition, 1):
    if '++' in shots:
        print(num, end=",")

print("\n")

for shots in competition:
    print(len(shots))

verseny.txt的内容是:

21
+--+
--+++-
-+--+--
++---
-++--
--+-+++----------------+-+
+-++--+
-+-+++-+
-+--+-+
--+++-
-+--+-
++--
-+--
-++----------------+-+
+-++-+--+
-+-+++-
-+--+-+-
++---+
-++-+-
--+-+++---+-------------+-+
+-++--+

2 个答案:

答案 0 :(得分:7)

问题是str(line.split())您基本上将"+--+\n"转变为"['+--+']"(其长度为8)。

而不是line.split()您可能打算使用line.strip()

答案 1 :(得分:1)

#Length of each lines appended in a list 
l=[]
for f in open('verseny.txt'):
    l.append(len(f))

print l



#if you want number of line in this file
count=-1
for f in open('verseny.txt'):
    count+=1
print count