退格在python中似乎不起作用

2024-10-01 09:36:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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,]

我是个新手…有人能帮忙吗?在


Tags: csvinforcloseoutputnetworkopenkeys
3条回答

为什么不使用str(dict)?在

for k, v in network.iteritems():
    output.write(str({k: v})[1:-1] + '\n')

使用^{}生成逗号分隔的值,以避免需要退格:

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

更简单的方法是,例如,list comprehensions迭代字典项:

>>> [output.write("%s:%s\n" % item) for item in network.items()]

"\b"只插入ASCII退格字符;它不会从输出文件中删除刚刚写入的字符。这就是为什么你的代码没有像你期望的那样运行。在

现在,修复它你可以更换

for ii1 in network.keys():
    output.write(repr(ii1)+":[")
    for n in network[ii1]:
        output.write(' %s,'%(repr(n)))
    output.write('\b'+']\n')

^{pr2}$

或者,为了进一步改善它

for k, v in network.items():
    print >>output, "%s:[ %s]" % (repr(k), ", ".join(map(repr, v)))

最后,如果键是简单的整数,那么repr(k)可以简化为k。另外,如果字典中的值是整数列表或类似的值,那么整个", ".join(map(repr, v))舞蹈可能是不必要的。在

相关问题 更多 >