2016-05-25 308 views
0

如何從字典分裂元組如何分割元組在Python

dic = {('K30', 'K56'): 1} 

得到這個輸出的文本文件:

K30 K56 1 

是我的嘗試是

for k,v in dic.items(): 
    a,b = k.split(',') 
    print >>f, a+'\t',b+'\t',v 
f.close() 

但我得到了錯誤:

AttributeError: 'tuple' object has no attribute 'split' 

回答

2

你不用拆,你可以簡單地說

a,b = k 
+1

或'爲(A,B), v in dic.items():' –

1

像這樣:

for k,v in dic.items(): 
print >>f, k[0]+'\t',k[1]+'\t',v f.close() 

只需訪問的元組元素。

1
for k,v in dic.items(): 
    print '\t'.join(k),'\t',v 
0

由於採取了所有的優秀人才,在這裏不用簡潔版本

[print(k[0],k[1],v) for k,v in dic.items()]