如何将集合中的条目连接成一个字符串?

基本上,我试图将一个集合中的条目连接起来,以便输出一个字符串。我尝试使用与列表的 join 函数类似的语法。下面是我的尝试:

list = ["gathi-109","itcg-0932","mx1-35316"]
set_1 = set(list)
set_2 = set(["mx1-35316"])
set_3 = set_1 - set_2
print set_3.join(", ")

但是我得到这个错误: AttributeError: 'set' object has no attribute 'join'

集合的等价调用是什么?

139242 次浏览

I think you just have it backwards.

print ", ".join(set_3)
', '.join(set_3)

The join is a string method, not a set method.

The join is called on the string:

print ", ".join(set_3)

Nor the set nor the list has such method join, string has it:

','.join(set(['a','b','c']))

By the way you should not use name list for your variables. Give it a list_, my_list or some other name because list is very often used python function.

You have the join statement backwards try:

print ', '.join(set_3)

Sets don't have a join method but you can use str.join instead.

', '.join(set_3)

The str.join method will work on any iterable object including lists and sets.

Note: be careful about using this on sets containing integers; you will need to convert the integers to strings before the call to join. For example

set_4 = {1, 2}
', '.join(str(s) for s in set_4)

Set's do not have an order - so you may lose your order when you convert your list into a set, i.e.:

>>> orderedVars = ['0', '1', '2', '3']
>>> setVars = set(orderedVars)
>>> print setVars
('4', '2', '3', '1')

Generally the order will remain, but for large sets it almost certainly won't.

Finally, just incase people are wondering, you don't need a ', ' in the join.

Just: ''.join(set)

:)

I wrote a method that handles the following edge-cases:

  • Set size one. A ", ".join({'abc'}) will return "a, b, c". My desired output was "abc".
  • Set including integers.
  • Empty set should returns ""
def set_to_str(set_to_convert, separator=", "):
set_size = len(set_to_convert)
if not set_size:
return ""
elif set_size == 1:
(element,) = set_to_convert
return str(element)
else:
return separator.join(map(str, set_to_convert))