首页 > 解决方案 > 如何从元组列表中添加值

问题描述

我正在从日志文件中提取并使用以下代码打印

for line in data:
    g = re.findall(r'([\d.]+).*?(GET|POST|PUT|DELETE)', line)
    print (g)

[('1.1.1.1', 'PUT')]
[('2.2.2.2', 'GET')]
[('1.1.1.1', 'PUT')]
[('2.2.2.2', 'POST')]

如何添加到输出

输出

1.1.1.1: PUT = 2
2.2.2.2: GET = 1,POST=1

标签: pythonlisttuplesadd

解决方案


您可以使用字典来计算:

# initialize the count dict
count_dict= dict()
for line in data:
    g = re.findall(r'([\d.]+).*?(GET|POST|PUT|DELETE)', line)
    for tup in g:
        # get the counts for tuple tup if we don't have it yet
        # use 0 (second argument to .get)
        num= count_dict.get(tup, 0)
        # increase the count and write it back
        count_dict[tup]= num+1
# now iterate over the key (tuple) - value (counts)-pairs
# and print the result
for tup, count in count_dict.items():
    print(tup, count)

好的,我不得不承认这并没有给出你想要的确切输出,但是你可以用类似的方式做到这一点:

out_dict= dict()
for (comma_string, request_type), count in count_dict.items():
    out_str= out_dict.get(comma_string, '')
    sep='' if out_str == '' else ', '
    out_str= f'{out_str}{sep}{request_type} = {count}'
    out_dict[comma_string]= out_str

for tup, out_str in out_dict.items():
    print(tup, out_str)

从您输出的数据中:

1.1.1.1 PUT = 2
2.2.2.2 GET = 1, POST = 1

推荐阅读