Python 打印不带括号的集合列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17750099/
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
Python print list of sets without brackets
提问by
I have a list of sets (using Python). Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
我有一个集合列表(使用 Python)。有没有办法在没有“set([])”东西的情况下打印它,只输出它们所持有的实际值?
Right now I'm getting somthing like this for each item in the list
现在我为列表中的每个项目得到这样的东西
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
我希望它看起来更像这样
blah,blahh,blahhh
回答by James Aylett
Lots of ways, but the one that occurred to me first is:
方法很多,但我首先想到的是:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print
. Should work in python 2 and python 3.
将集合中的所有内容转换为字符串,并用逗号将它们连接在一起。显然,您对显示的偏好可能会有所不同,但您可以很高兴地将其传递给print
. 应该在 python 2 和 python 3 中工作。
For list of sets:
对于集合列表:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))
回答by FastTurtle
I'm assuming you want a string representation of the elements in your set. In that case, this should work:
我假设您想要集合中元素的字符串表示形式。在这种情况下,这应该有效:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__
method, so keep that in mind when printing out elements in your set.
但是,这取决于具有__str__
方法的 s 元素,因此在打印集合中的元素时请记住这一点。
回答by murgatroid99
Assuming that your list of sets is called set_list
, you can use the following code
假设您的集合列表被调用set_list
,您可以使用以下代码
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list
is equal to [{1,2,3}, {4,5,6}]
, then the output will be
如果set_list
等于[{1,2,3}, {4,5,6}]
,则输出将是
1, 2, 3
4, 5, 6