2012-12-15 144 views
-3

我正在讓用戶輸入一個文件來打開包含數字的文件。我希望輸出成爲文件中元素的數量。我把..Python中列表的長度?

file=open(input("Please enter the name of the file you wish to open:"))#, "r") 
A= file.readline() 

print (A) 

n=len(A) 
print (n) 

我很新的這一點。我正在測試的文件有9個數字(其中2個是負數)。長度出來到21.我怎麼能改變這個來獲取元素的數量?

+0

該文件如何查看?每行一個號碼?數字用空格分隔? – Tim

+0

輸入文件的格式是什麼?他們是用空格還是逗號分隔?具體的例子在這裏會有所幫助。 –

+0

是(如:1 -3 10 6 5 0 3 -5 20) – user1906407

回答

5

如果數字都是在該行,使用split字符串成單獨的數字分開:

# List of strings: ['1', '-3', '10', ...] 
numbers = A.split() 

print len(numbers) 

您可能還需要這些數字從字符串形式轉換爲int形式:

# List of numbers: [1, -3, 10, ...] 
numbers = [int(n) for n in A.split()] 
+0

謝謝!我錯過了 – user1906407