python - 如何从元组列表中添加值
问题描述
我正在从日志文件中提取并使用以下代码打印
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
解决方案
您可以使用字典来计算:
# 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
推荐阅读
- tfrecord - TensorFlow 对象检测 API tfrecord
- python - 将对象传递到类实例内的选项卡中
- vba - Excel 宏有时有效,有时无效
- spring-boot - Swagger @ApiModel 值被忽略
- ios - RxSwift Driver 弱订阅?
- python - 使用正确的 ReLU 导数会阻止学习
- regex - 如何在单词的开头或单词内部找到三个相同的字母
- ms-access - 仅在 Access 报表中更改当前记录的控件属性
- sql - 将 Pivot 从 Oracle 转换为 SQL Server
- c++ - 如何找到连接 ASCII 和 std::string 的子字符串?