如何将一组中的条目连接到一个字符串中?
基本上,我试图将一组中的条目连接在一起以输出一个字符串。我正在尝试使用类似于列表连接函数的语法。这是我的尝试:
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'
对集合的等效调用是什么?
Basically, I am trying to join together the entries in a set in order to output one string. I am trying to use syntax similar to the join function for lists. Here is my attempt:
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(", ")
However I get this error: AttributeError: 'set' object has no attribute 'join'
What is the equivalent call for sets?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
join
是一个字符串方法,而不是一个集合方法。The
join
is a string method, not a set method.集合没有
join
方法,但您可以使用 改为str.join
。str.join
方法适用于任何可迭代对象,包括列表和集合。注意:在包含整数的集合上使用此方法时要小心;您需要在调用 join 之前将整数转换为字符串。例如
Sets don't have a
join
method but you can usestr.join
instead.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
对字符串调用
join
:The
join
is called on the string:集合没有顺序 - 因此,当您将列表转换为集合时,您可能会丢失顺序,即:
通常,顺序将保留,但对于大型集合,几乎肯定不会。
最后,以防万一人们想知道,您不需要在连接中使用“,”。
只是: ''.join(set)
:)
Set's do not have an order - so you may lose your order when you convert your list into a set, i.e.:
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)
:)
set
和list
都没有这样的方法join
,字符串有它:顺便说一下,你不应该使用名称
list 为你的变量。给它一个
list_
、my_list
或其他名称,因为list
是经常使用的 python 函数。Nor the
set
nor thelist
has such methodjoin
, string has it:By the way you should not use name
list
for your variables. Give it alist_
,my_list
or some other name becauselist
is very often used python function.您可以向后尝试 join 语句:
You have the join statement backwards try:
我认为你只是把事情搞反了。
I think you just have it backwards.
我编写了一个处理以下边缘情况的方法:
", ".join({'abc'})
将返回"a, b, c"
。我想要的输出是“abc”
。""
I wrote a method that handles the following edge-cases:
", ".join({'abc'})
will return"a, b, c"
. My desired output was"abc"
.""