如何在 Python 中打印不带括号的元组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19112735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a list of tuples with no brackets in Python
提问by Boosted_d16
I'm looking for a way to print elements from a tuple with no brackets.
我正在寻找一种从没有括号的元组中打印元素的方法。
Here is 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
但我收到以下错误
AttributeError: '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
采纳答案by TerryA
mytuple
is already a list (a list of tuples), so calling list()
on it does nothing.
mytuple
已经是一个列表(元组列表),因此调用list()
它没有任何作用。
(1.0,)
is a tuple with one item. You can't call string functions on it (like you tried). They're for string types.
(1.0,)
是一个包含一项的元组。你不能在它上面调用字符串函数(就像你试过的那样)。它们用于字符串类型。
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
回答by Bertrand Ptheitroadot
You can do it like this as well:
你也可以这样做:
mytuple = (1,2,3)
print str(mytuple)[1:-1]
回答by Liron Lavi
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 + ','
回答by SmartManoj
mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)]
for item in mytuple:
print(*item) # *==> unpacking