簡體   English   中英

Python打印列表問題

[英]Python Printing A List Issue

我真的很努力找出如何打印到列表。 我想打印我指定的URL的服務器響應代碼。 您知道我將如何更改代碼以將輸出打印到列表中嗎? 如果沒有,您知道我在哪里找到答案嗎? 我已經搜索了幾個星期了。

這是代碼:

import urllib2
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

打印:

200

200

我想擁有:

[200, 200]

您實際上想要一張清單嗎? 還是只是像列表一樣打印? 在這兩種情況下,以下均應起作用:

import urllib2
out = []
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]:
    try:
        connection = urllib2.urlopen(url)
        out.append(connection.getcode())
        connection.close()
    except urllib2.HTTPError, e:
        out.append(e.getcode())
print out

它只是制作一個包含代碼的列表,然后打印該列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM