如何将多个词典的内容保存到一个词典中,然后将其保存在for循环中的列表中



下面的代码运行良好。我想知道是否有可能在几个行代码(行(中运行相同的代码,只将内容保存在一个字典中,例如(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-4F114AA3888 iOS13.6.1 5U1XW8wkoqUPCTGhC1ni9Whinvt1 2020-11-13 22:28:55.029000+00:00学生档案学生00mrvPyS9Y2Al9iTN1vw 1231534.547

2 1.6.1.44 10.0.216 40a4dc7cb837fdec Android10 27lFw6EnfbYFsU3F8EejYGQRRl1 2020-11-12 21:28:00.998000+00:00公司设置公司01dMOvAgsRTPSWXTDXIh 1141480.516

  1. mhist字典转换为字典中的List
mhist, mhist1, mhist2, mhist3, mhist4 = {}, {}, {}, {}, {}
mhist_list = [mhist, mhist1, mhist2, mhist3, mhist4]

现在,字典在List中。

  1. 现在,我们有一个包含5个字典的列表,还有5个if。这可以用于根据请求将代码收缩为for循环
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:
for x in range(1,6):
if float(line[10]) <= float(x * 21600):
if IpAddress in mhist_list[x-1].keys():
mhist_list[x-1][IpAddress].append(str(time))
else:
mhist_list[x-1][IpAddress] = [str(time)]
n+=1  
  1. 打印mhist_list现在应该会将字典作为List提供
print(mhist_list)

现在应该可以了。

相关内容

  • 没有找到相关文章

最新更新