数组元素的Python求和
我有以下行的文件:数组元素的Python求和,python,arrays,file,Python,Arrays,File,我有以下行的文件: date:ip num#1 num#2 2013.09:142.134.35.17 10 12 2013.09:142.134.35.17 4 4 2013.09:63.151.172.31 52 13 2013.09:63.151.172.31 10 10 2013.09:63.151.172.31 16 32 2013.10:62.151.172.31 16 32 我如何总结相同IP的最后两个元素来得出这样的结论 2013.09:142.134.35.17 14
date:ip num#1 num#2
2013.09:142.134.35.17 10 12
2013.09:142.134.35.17 4 4
2013.09:63.151.172.31 52 13
2013.09:63.151.172.31 10 10
2013.09:63.151.172.31 16 32
2013.10:62.151.172.31 16 32
我如何总结相同IP的最后两个元素来得出这样的结论
2013.09:142.134.35.17 14 16
2013.09:63.151.172.31 78 55
2013.10:62.151.172.31 16 32
试试这个:
from collections import Counter
with open('full_megalog.txt') as f:
data = [d.split() for d in f]
sum1, sum2 = Counter(), Counter()
for d in data:
sum1[d[0]] += int(d[1])
sum2[d[0]] += int(d[2])
for date_ip in sum1.keys():
print date_ip, sum1[date_ip], sum2[date_ip]
您可以这样做:
addrs='''\
2013.09:142.134.35.17 10 12
2013.09:142.134.35.17 4 4
2013.09:63.151.172.31 52 13
2013.09:63.151.172.31 10 10
2013.09:63.151.172.31 16 32
2013.10:62.151.172.31 16 32'''
class Dicto(dict):
def __missing__(self, key):
self[key]=[0,0]
return self[key]
r=Dicto()
for line in addrs.splitlines():
ip,n1,n2=line.split()
r[ip][0]+=int(n1)
r[ip][1]+=int(n2)
print r
# {'2013.09:142.134.35.17': [14, 16],
'2013.09:63.151.172.31': [78, 55],
'2013.10:62.151.172.31': [16, 32]}
或者,如果您愿意,使用defaultdict:
from collections import defaultdict
r=defaultdict(lambda: [0,0])
for line in addrs.splitlines():
ip,n1,n2=line.split()
r[ip][0]+=int(n1)
r[ip][1]+=int(n2)
print r
您可以使用字典帮助您解决问题,如下所示:
#assuming that your addresses are stored in a file:
with open('addresses.txt', 'r') as f:
lines = f.readlines()
ele = {}
for line in lines:
addr = line.split()
s = [int(addr[1]), int(addr[2])]
if addr[0] in ele:
ele[addr[0]][0] += s[0]
ele[addr[0]][1] += s[1]
else:
ele[addr[0]] = s
这将为您提供:
{'2013.09:142.134.35.17': [14, 16],
'2013.09:63.151.172.31': [78, 55],
'2013.10:62.151.172.31': [16, 32]}
编辑了@piokuc的答案,因为他特别要求ip,而不是日期+ip。 拆分和求和仅在ip上完成
from collections import Counter
import re
data=\
"""2012.09:142.134.35.17 10 12
2013.09:142.134.35.17 4 4
2013.09:63.151.172.31 52 13
2013.09:63.151.172.31 10 10
2013.09:63.151.172.31 16 32
2013.10:62.151.172.31 16 32"""
data = [re.split('[: ]',d) for d in data.split('\n')]
print data
sum1 = Counter()
sum2 = Counter()
for d in data:
sum1[d[1]] += int(d[2])
sum2[d[1]] += int(d[3])
for date_ip in sum1.keys():
print date_ip, sum1[date_ip], sum2[date_ip]
@皮奥库克的回答很好;这是一个简单的解决方案,初学者应该很容易理解,而不必进入
计数器的标准库
您要查找的结果是由两个(有序的)值组成的,每个值都与一个唯一的标签(日期:ip
值)关联。在Python中,这类任务的基本数据结构是dict(字典)
打开文件以确保在不再需要文件时将其关闭是一种很好的做法。为此,我将使用和语句;如果您对其工作原理的更多细节感兴趣,但如果您对此不感兴趣,请记住,一旦with
块结束,您正在使用的文件将自动关闭
下面是代码-请记住,从文件中读取的所有内容都将作为字符,这意味着您必须在对数字执行任何类型的数学运算之前对其进行适当的转换:
result = {} # Create your empty dict
with open('full_megalog.txt', 'r') as file: # Open your input file
for line in file: # In each line of the file:
date_ip, num1, num2 = line.split() # 1: Get key and 2 values
if date_ip in result: # 2: Check if key exists
result[date_ip][0] += int(num1) # 3a: If yes, add num1, num2
result[date_ip][1] += int(num2) # to current sum.
else: # 3b: If no, add the new key
result[date_ip] = int(num1), int(num2) # and values to the dict
现在您有了一个结果
字典,它将num1
和num2
的总和与每个相应的日期
关联起来。您可以使用结果[date\u ip]
访问(num1,num2)
元组,也可以使用结果[date\u ip][0]
和结果[date\u ip][1]
分别访问值
如果您想以原始格式编写,则必须使用空格字符将每个键和两个值连接在一起;冗长、易于评论的方法可能是:
with open('condensed_log_file.txt', 'w') as out: # open the output file;
for date_ip in result: # loop through the keys;
out.write( # write to the logfile:
' '.join( # joined by a space char,
(date_ip, # the key (date_ip);
str(result[date_ip][0]), # the 1st value (num1);
str(result[date_ip][1])) # & the 2nd value (num2).
)
我很想看看piokuc非常简洁的方法和我自己天真的方法之间的性能比较。这没有打印和输出文件写入语句:
>>> from timeit import timeit
>>> a = open("airthomas.py", "r")
>>> a = a.read()
>>> p = open("piokuc.py", "r")
>>> p = p.read()
>>> timeit(p)
115.33428788593137
>>> timeit(a)
103.95908962552267
因此,如果您需要在大量小文件上运行此操作,那么使用Counter()
可能会稍微慢一点。当然,您可能只需要在一个或几个非常大的文件上运行它——在这种情况下,您可以自己进行测试;PQ:你尝试过什么?我已经做过:file=open(“full_megalog.txt”,“r”)文件中的行:@JohnSmith这不算尝试\是否确实要对只有相同IP的元素求和,或者它们也需要在相同的日期出现,即具有相同的日期:IP
值?为什么使用计数器
,为什么不使用默认dict(int)
?对于计数器
来说,这不是一个很好的用例。恐怕我不同意你的说法,这是计数器
的一个很好的用例。听到讨论双方的原因会很有建设性。@TankorSmash我已经给出了一个解释:一个简单的,工作解决方案非常简单。@1\u CR--计数器
的工作原理与defaultdict(int)
非常相似,只是它有一系列其他有用的方法,您可以在以后使用。。。我认为这是对计数器的一种使用,尽管它肯定没有展示计数器可以做的所有整洁的事情:)