2013-11-23 131 views
0

如何打印列表?打印出列表

def main(): 
    fileName = input("Please input name of file to read: ") 
    fileOpen = open(fileName) 
    lineList = fileOpen.readlines() 
    print("Hercules' Strategy:", lineList[len(lineList)-3].strip()) 
    print("Initial Hydra heads:",lineList[len(lineList)- 2].strip()) 
    print("Hydra growth period:", lineList[len(lineList)-1].strip()) 

main() 

文本文件:

smallest 
8 7 3 
10 

電流輸出:

Hercules' Strategy: smallest 
Initial Hydra heads: 8 7 3 
Hydra growth period: 10 

我想獲得的輸出是認爲:

Hercules' Strategy: smallest 
Initial Hydra heads: [8, 7, 3] 
Hydra growth period: 10 
+0

這不是我想的清單。這只是一個字符串。如果你只是想要支架,爲什麼不'print'['+ you_string +']'' – gongzhitaao

+0

@ gzhngzhitaao是的。這是我現在的問題。我想打印出列表,而不是字符串。 – user2985771

+0

所以你真的想把字符串解析成一個列表? – gongzhitaao

回答

0

就分割字符串和打印它就像這樣的數字

print("Initial Hydra heads:",list(map(int, lineList[len(lineList)-2].strip().split()))) 

由於Hyperboreus建議,如果你想在一個列表中的數據,可以使用負索引與列表,所以下面是一樣的前行

print("Initial Hydra heads:",list(map(int, lineList[-2].strip().split()))) 
+0

我得到了這個輸出:'初始Hydra頭:<地圖對象在0x104929b10>' – user2985771

+0

@ user2985771我想你使用Python 3.請現在檢查我的答案 – thefourtheye

+0

謝謝!對不起,花了一段時間接受你的文章作爲答案! – user2985771

0

,你也可以加入列表轉換爲字符串,像這樣:

joinedList = "[" + ", ".join(lineList[len(lineList)-3]) + "]" 

如果你不是在具有數據列表實際上有興趣,你應該只處理字符串轉換成你想要的格式,thefourtheye建議。