簡體   English   中英

Python For-Loop Output 列模式

[英]Python For-Loop Output Column Patterns

我正在嘗試以列格式處理 output 數據。

我嘗試了兩種方法,第一種用於測試目的; 調用數據集中已識別的值(在測試期間限制運行時間)。 第二種方法利用 for 循環從數據集中提取所有數據。 但是,第二種方法 output 的列模式與我預期的不同。

我從中提取數據的每個 HTML 頁面都有不可預測的項目數量,這些項目將附加到列表中,因此單獨列出它們(如方法 1 中所示)將不起作用。

這是代碼的概述及其結果的顯示:

方法一代碼:

for num in range(1, 3):
    url = "https://test.com/testid={}".format(num)
    # [. . . ]
    set = soup.find_all('td') # call to pull data
    a = set[0]
    b = set[1]
    c = set[2]
    info = [a,b,c]
    print(info)

方法1 Output:

Column 1: a, b, c

Column 2: a, b, c

方法二代碼:

for num in range(1, 3):
    url = "https://test.com/testid={}".format(num)
    # [. . . ]
    set = soup.find_all('td') # call to pull data
    info = []
    for data in set:    
        info.append(data)
    print(info)

方法2 Output:

Column 1: a, b, c, a, b, c

有人知道為什么方法 2 沒有產生相同的 output 列模式或者我可能會怎么做? 謝謝

嘗試首先獲取所需的,然后是表行(tr),然后是表數據(td)。

table = soup.find("table") # get the table
table_data = table.tbody.find_all("tr")  # get the table rows (tr)

data = []
for i in table_data[0].find_all("td"): # get the table data (td)
    data.append(i.text)

print(data)

我知道這並不酷,但我第二天早上第一件事就想通了,我想我只是需要重新審視一下。 我需要像方法 1 中那樣將數據集分割成列表項,並像方法 2 中那樣調用所有項。經過一些測試后,我發現問題在於 .append 調用(我不確定為什么它的屬性是這樣的它沒有以與手動將值添加到列表中相同的方式分割數據?)因此,我創建了一個自動從頭到尾跨越的列表,以繞過 .append 調用。 像這樣:

for num in range(1, 3):
    url = "https://test.com/testid={}".format(num)
    # [. . . ]
    set = soup.find_all('td') # call to pull data
    info = td[0:-1] #segments list items but also calls the full list
    print(info)

暫無
暫無

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

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