【发布时间】:2020-12-25 06:36:20
【问题描述】:
下面的代码运行良好。我想知道是否有可能通过仅将内容保存在一个字典中(例如(mhist))在几个行代码(行)中运行相同的代码,然后将该字典的内容保存在一个列表中在 for 循环中。
这是我的代码:
fn = 'screenviewclean.1.csv'
f = open(fn,"r")
reader = csv.reader(f)
n = 0
i=0
mhist = {}
mhist1 = {}
mhist2 = {}
mhist3 = {}
mhist4 = {}
for line in reader:
i+=1
sec= line [10]
IpAddress = line [2]
timeStamp = line [6]
time = timeStamp[11:13]+ timeStamp[13:19]
Day = timeStamp[0:10]
if i>1:
if float(line[10]) <= float(21600):
if IpAddress in mhist.keys():
mhist[IpAddress].append(str(time))
else:
mhist[IpAddress] = [str (time)]
if float(line[10]) > float(21600) and float(line[10]) <= float(43200) :
if IpAddress in mhist1.keys():
mhist1[IpAddress].append(str(time))
else:
mhist1[IpAddress] = [str (time)]
if float(line[10]) > float(43200) and float(line[10]) <= float(64800) :
if IpAddress in mhist2.keys():
mhist2[IpAddress].append(str(time))
else:
mhist2[IpAddress] = [str (time)]
if float(line[10]) > float(64800) and float(line[10]) <= float(86400) :
if IpAddress in mhist3.keys():
mhist3[IpAddress].append(str(time))
else:
mhist3[IpAddress] = [str (time)]
if float(line[10]) > float(86400) and float(line[10]) <= float(108000) :
if IpAddress in mhist4.keys():
mhist4[IpAddress].append(str(time))
else:
mhist4[IpAddress] = [str (time)]
n+=1
print (mhist)
print (mhist1)
print (mhist2)
print (mhist3)
print (mhist4)
这是我拥有的数据集的两行:
未命名:0 lastLoggedVersion IpAddress deviceId deviceOS userId timeStamp screenName userType doc.id seconds
0 1.6.0.1 192.168.0.77 7612F62D-E392-4269-B49B-4F1214AA3888 IOS13.6.1 5U1XW8WKOQUPCTGHC1NI9WHINVT1 2020-11-13 22:28:55.029000 + 00:00学生预防学生00MRVPYS9Y2AL9ITN1VW 1231534.547
2 1.6.1.44 10.0.2.16 40a4dc7cb837fdec Android10 27lFw6EnfbYFsU3F8AEejYGQRRl1 2020-11-12 21:28:00.998000+00:00 CompanySettings 公司 01dMOvAgsRTPSWXTDXI16h 1141480.
。【问题讨论】:
-
您打算如何将
dictionary保存为List?dictionary将值与字典中的每个键相关联。将dictionary保存为List意味着您将失去此关联(每个IP 地址与时间戳的关联),除非您不关心此关联。您是否要将dictionary中的每个值都放入List中? -
很抱歉造成混乱。我正在寻找创建许多字典,其中每个字典都有许多 ip 地址(作为键)和每个字典的许多值(例如:'192.168.1.240': ['16:23:40', '16:23:39 ', '16:23:20']) 之后,我希望将这些字典保存到几行代码中的字典列表中。这是我正在寻找的示例 [{''192.168.1.240': ['16:23:40', '16:23:39', '16:23:20'], '192.168.0.242' : ['20:14:07', '20:14:09']}]。
-
感谢您的澄清。现在这是有道理的。我将为您制定解决方案。
-
另外,您的字典在最后打印时是否正常工作?就像您期望的值/数据一样?我想首先确保字典符合您的期望。
-
是的,当我最后打印它们时,它们都可以正常工作。
标签: python python-3.x list csv dictionary