network={1:[2,3,4],2:[1,3,4], 3:[1,2], 4:[1,3,5], 5:[6,7,8], 6:[5,8],7:[5,6], 8:[5,6,7]}
str1='network.csv'
output = open(str1,'w')
for ii1 in network.keys():
output.write(repr(ii1)+":[")
for n in network[ii1]:
output.write(' %s,'%(repr(n)))
output.write('\b'+']\n')
output.close()
我所期望的是:
^{pr2}$但我得到的是:
1:[ 2, 3, 4,]
2:[ 1, 3, 4,]
3:[ 1, 2,]
4:[ 1, 3, 5,]
5:[ 6, 7, 8,]
6:[ 5, 8,]
7:[ 5, 6,]
8:[ 5, 6, 7,]
我是个新手…有人能帮忙吗?在
为什么不使用
str(dict)
?在使用^{} 生成逗号分隔的值,以避免需要退格:
更简单的方法是,例如,list comprehensions迭代字典项:
"\b"
只插入ASCII退格字符;它不会从输出文件中删除刚刚写入的字符。这就是为什么你的代码没有像你期望的那样运行。在现在,修复它你可以更换
与
^{pr2}$或者,为了进一步改善它
最后,如果键是简单的整数,那么
repr(k)
可以简化为k
。另外,如果字典中的值是整数列表或类似的值,那么整个", ".join(map(repr, v))
舞蹈可能是不必要的。在相关问题 更多 >
编程相关推荐