我有两个列表,并将这两个列表合并到字典中:
ip = ["1.1.1.1", "2.2.2.2", "3.3.3.3", " 4.4.4.4", "5.5.5.5", "6.6.6.6", "7.7.7.7"]
name = ["ip0", "ip2", "ip2", "ip3", "ip3", "ip3"]
{'ip2': "['2.2.2.2', '3.3.3.3']", 'ip3': "[' 4.4.4.4', '5.5.5.5', '6.6.6.6']", 'ip0': "['1.1.1.1']"}
我想将此词典导出为CSV文件 key在一个单元格中,配对值也应该在下一个单元格中,并且此单元格中应该有多个行用于ip地址。 例如:
ip2 2.2.2.2
3.3.3.3
我应该怎么做?
结合两个列表配置:
k = list(zip(name, ip))
d = {}
for (x,y) in k:
if x in d:
d[x] = d[x] +","+ y
else:
d[x] = y
答案 0 :(得分:0)
好的,现在我明白了你的意思。以下是更新答案的示例:
print('op:',sess.run(acc_op,{logits:[[0,1,0],[0,1,0]]}))
#op: 0.75
print('[total, count]:',sess.run(stream_vars))
#[total, count]: [3.0, 4.0]
“output.csv”:
ip = ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4", "5.5.5.5", "6.6.6.6", "7.7.7.7"]
name = ["ip0", "ip2", "ip2", "ip3", "ip3", "ip3"]
# Create dictionary
# We use setdefault to list ([]) here to be able to append values to list
# if it does not exist yet.
#d = {}
#for x,y in list(zip(name,ip)):
# d.setdefault(x, []).append(y)
# But to use your example we can use this small modification:
k = list(zip(name, ip))
d = {}
# Create dictionary
for (x,y) in k:
if x in d:
d[x] += [y]
else:
d[x] = [y]
# Output dictionary
with open("output.csv", "w") as f:
for k,v in d.iteritems(): # d.items() if py3
for ind,item in enumerate(v):
if ind == 0:
f.write("{},{}\n".format(k,item))
else:
f.write(",{}\n".format(item))
字典现在看起来像这样:
ip0,1.1.1.1
ip2,2.2.2.2
,3.3.3.3
ip3,4.4.4.4
,5.5.5.5
,6.6.6.6