2013-10-01 98 views
8

我正在寻找一种方法来打印从元组元素没有括号Python中没有括号

我的继承人元组打印的元组元素它更容易与

mylist == list(mytuple) 

然后我做了以下

for item in mylist: 
    print item.strip() 
工作3210

,但我得到以下错误

'tuple' object has no attribute 'strip' 

,因为我认为我转换到一个列表中这是很奇怪吗?

我所希望看到的最终结果是一样的东西

1.0, 
25.34, 
2.4, 
7.4 

1.0, ,23.43, , 2.4, ,7.4 

感谢

+5

你真正想要的双逗号? –

回答

8

mytuple已经是一个列表(元组的列表),因此调用list()就没有做任何事情。

(1.0,)是一个包含一个项目的元组。你不能调用它的字符串函数(就像你试过的)。它们适用于字符串类型。

要在您的元组的清单打印的每一个项目,只是做:

for item in mytuple: 
    print str(item[0]) + ',' 

或者:

print ', ,'.join([str(i[0]) for i in mytuple]) 
# 1.0, ,25.34, ,2.4, ,7.4 
+1

会'print',,'。join(map(str,mytuple))'做同样的事情吗? –

+1

@Mr_and_Mrs_D没有,因为我们需要'我[我] [而不是'我为我' – TerryA

4

你可以像下面这样做还有:

mytuple = (1,2,3) 
print str(mytuple)[1:-1] 
0

我迭代遍历列表元组,比我遍历元组的'项目'。

my_tuple_list = [(1.0,),(25.34,),(2.4,),(7.4,)] 

for a_tuple in my_tuple_list: # iterates through each tuple 
    for item in a_tuple: # iterates through each tuple items 
     print item 

结果:

1.0 
25.34 
2.4 
7.4 

,达到您上面你提到的结果可以随时添加

print item + ',' 
0
mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)] 
for item in mytuple: 
    print(*item) # *==> unpacking