在Python中打印集时删除集标识符

时间:2013-03-10 22:58:35

标签: python python-2.7 set

我正在尝试打印出一组内容,当我这样做时,我在打印输出中得到了set identifier。例如,对于下面的代码,这是我的输出set(['a', 'c', 'b', 'e', 'd', 'f', 'gg', 'ff', 'jk'])“。我想删掉单词set。我的代码很简单,位于下面。

infile = open("P3TestData.txt", "r")
words = set(infile.read().split())
print words

这是我的输出,以便于参考:set(['a', 'c', 'b', 'e', 'd', 'f', 'gg', 'ff', 'jk'])

4 个答案:

答案 0 :(得分:45)

您可以将该设置转换为列表,仅用于打印:

print list(words)

或者您可以使用str.join()以逗号加入集合的内容:

print ', '.join(words)

答案 1 :(得分:3)

print语句使用set的{​​{1}}实现。你可以:

  1. 推出自己的打印功能,而不是使用__str__()。获得更好格式的简单方法可能是使用print的{​​{1}}实现:

    list

  2. 覆盖您自己的__str__()子类中的print list(my_set)实现。

答案 2 :(得分:1)

如果你想要花括号,你可以这样做:

>>> s={1,2,3}
>>> s
set([1, 2, 3])
>>> print list(s).__str__().replace('[','{').replace(']','}')
{1, 2, 3}

或者,使用格式:

>>> print '{{{}}}'.format(', '.join(str(e) for e in set([1,'2',3.0])))
{3.0, 1, 2}

答案 3 :(得分:1)

如果在Python 3中打印一组数字,您也可以使用切片。

Python 3.3.5
>>> s = {1, 2, 3, 4}
>>> s
{1, 2, 3, 4}
>>> str(s)[1:-1]
'1, 2, 3, 4'

当移植回Python2时,这并不能很好地转换......

Python 2.7.6
>>> s = {1, 2, 3, 4}
>>> str(s)[1:-1]
'et([1, 2, 3, 4]'
>>> str(s)[5:-2]
'1, 2, 3, 4'

另一方面,要join()整数值,您必须先转换为字符串:

Python 2.7.6
>>> strings = {'a', 'b', 'c'}
>>> ', '.join(strings)
'a, c, b'
>>> numbers = {1, 2, 3, 4}
>>> ', '.join(numbers)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> ', '.join(str(number) for number in numbers)
'1, 2, 3, 4'

然而,这仍然比切片更正确。