Python - print tuple elements with no brackets

試著忘記壹切 提交于 2019-12-04 08:23:08

问题


I'm looking for a way to print elements from a tuple with no brackets

Heres my tuple:

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

I converted this to a list to make it easier to work with

mylist == list(mytuple)

then i did the following

for item in mylist:
    print item.strip()

but i get the following error

'tuple' object has no attribute 'strip'

which is strange because I thought i converted to a list?

what I expect to see as the final result is something like

1.0,
25.34,
2.4,
7.4

or

1.0, ,23.43, , 2.4, ,7.4 

Thanks


回答1:


mytuple is already a list (a list of tuples), so calling list() on it does nothing.

(1.0,) is a tuple with one item. You can't call string functions on it (like you tried). They're for string types.

To print each item in your list of tuples, just do:

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

Or:

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



回答2:


You can do it like this as well:

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



回答3:


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



回答4:


I iterate through the list tuples, than I iterate through the 'items' of the tuples.

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

result:

1.0
25.34
2.4
7.4

to get exactly the result you mentioned above you can always add

print item + ','


来源:https://stackoverflow.com/questions/19112735/python-print-tuple-elements-with-no-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!