Skip to main content
 首页 » 编程设计

python之退格键似乎在 python 中不起作用

2025年05月04日11bjzhanghao

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() 

我期望的是这样的:

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] 

但我得到的是:

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

我是新手....有人可以帮忙吗?

请您参考如下方法:

"\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') 

与

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

或者,进一步改进它,用

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

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