2017-04-20 4 views
1

Ich habe eine Datei und ich möchte die Länge der Zeilen erhalten.Python len() nicht gut

Aber wenn ich die Länge:

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

Es ist mein Code:

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

der Inhalt verseny.txt ist:

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

Antwort

7

Das Problem ist str(line.split()) Sie drehen im Wesentlichen "+--+\n" in "['+--+']" (die eine Länge von 8 hat).

Anstelle von line.split() wollten Sie wahrscheinlich line.strip() verwenden.

+0

Dies ist die Lösung! : D Danke! – Giton22

+0

oder 'line.rstrip()', um nur nach rechts zu entfernen. –

+0

@ Giton22 Wenn das die Lösung ist, einfach die Antwort akzeptieren. –

0
#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 
Verwandte Themen