2013-11-23 125 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建议。