打印出列表

时间:2013-11-23 04:34:58

标签: python list

我如何打印清单?

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

TEXTFILE:

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

2 个答案:

答案 0 :(得分: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())))

答案 1 :(得分:0)

如果您想要列表中的数据,您还可以将列表加入到如下字符串中:

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

如果您实际上并不想将数据作为列表,那么您应该将字符串处理为您想要的格式,如下所示。