【问题标题】:Printing out the List打印列表
【发布时间】:2013-11-23 04:34:58
【问题描述】:

我将如何打印列表?

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

【问题讨论】:

  • 这不是我认为的列表。它只是一个字符串。如果你只想要括号,为什么不print '[' + you_string + ']'
  • @gongzhitaao 是的。这就是我现在的问题。我想打印出列表,而不是字符串。
  • 所以你真的想把字符串解析成一个列表?

标签: python list


【解决方案1】:

只需拆分字符串并将其打印为这样的数字

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

【讨论】:

  • 我得到了这个输出:Initial Hydra heads: <map object at 0x104929b10>
  • @user2985771 我认为您使用的是 Python 3。请立即查看我的答案
  • 谢谢!抱歉,接受您的帖子作为答案需要一段时间!
  • len(lineList)-2代替-2有什么魔力?
  • @Hyperboreus 我包含了你的建议 :)
【解决方案2】:

如果你想要一个列表中的数据,你也可以像这样将列表连接成一个字符串:

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

如果您实际上对将数据作为列表不感兴趣,则应该按照 thefourtheye 的建议将字符串处理成您想要的格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多