簡體   English   中英

從列表項創建字典

[英]Create a dictionary from list items

以下代碼為我提供了如下所示的輸出。 我想將各個類別后面的數字都放入字典中。 這樣做的有效方法是什么?

當前代碼:

d = {}
data = []

contentB = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr/td")

for a in contentB:
    a = a.text_content().strip()
    data.extend(a.splitlines())

for item in data:

    if re.match(r'\(\d+', item) is not None:
        item = item.replace('(', '-').replace(')', '')

        print(item)

輸出量

Period Ending
Total Revenue
31821000
30871000
29904000
Cost of Revenue
16447000
16106000
15685000
Gross Profit
15374000
14765000
14219000
Operating Expenses
Research Development
1770000
1715000
1634000

期望的結果

{
    'Total Revenue': [31821000, 30871000, 29904000],
    'Cost of Revenue': [16447000, 16106000, 15685000],
    'Gross Profit': [15374000, 14765000, 14219000]
}

像這樣:

output = {}
current_key = None
for item in data:
    if re.match(r'\(\d+', item) is None:
        current_key = item.replace('(', '-').replace(')', '')
        output[current_key] = []
    else:
        if current_key:
            output[current_key].append(int(item.replace(',', '')))

print output

與@Eugene Soldatov的答案類似,我嘗試自動識別數據中斷。 我使用的是語言環境軟件包,因為您的數據似乎使用逗號分隔單元。 您可能必須將第二行調整為您的區域設置。 未經測試,因為我不使用具有該格式的語言環境;-)

import locale
#locale.setlocale(locale.LC_ALL, 'en_US.UTF8')

summary = {}
current_key = None
for line in data:
    try
        if current_key:
            summary[current_key].append(locale.atoi(line.strip()))
    except ValueError:
        current_key = line.strip()
        summary[current_key] = []

暫無
暫無

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

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