从列表项创建字典

2024-04-26 01:07:01 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码给出如下所示的输出。我想把每一个数字,在各自的类别,并把他们放入字典。什么是有效的方法?你知道吗

当前代码:

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]
}

Tags: of代码infordatatableitemtr
2条回答

与@Eugene Soldatov的答案类似,我尝试自动识别数据中断。不过,我使用的是locale包,因为您的数据似乎使用逗号来分隔单位。您可能需要根据您的区域设置调整第二行。未测试,因为我不使用具有该格式的区域设置;-)

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] = []

像这样:

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

相关问题 更多 >