Python 2.7中的return

刚才那个代码有误,我把全部贴出来
class intSet(object):

def __init__(self):
    # creat an empty set of integers
    self.vals = []

def insert(self, e):
    # assume e is an interger, and insert it 
    if not(e in self.vals):
        self.vals.append(e)

def member(self, e):
    return e in self.vals

def remove(self, e):
    try:
        self.vals.remove(e)
    except:
        raise ValueError(str(e) + 'not found')


def __str__(self):
    # return a string representation of self
    self.vals.sort()
    return "{" + ','.join([str(e) for e in self.vals]) + "}"

初学,return后面这一句依然没看懂 .join在这里是method吗, 这个格式是怎么回事

阅读 4.3k
3 个回答

(1)join(...)
S.join(iterable) -> string

Return a string which is the concatenation of the strings in the
iterable.  The separator between elements is S.

join的作用是将一个字符迭代对象拼接成一个字符串。中间用S分割,","就是S,即用逗号分割。
(2)[str(e) for e in self.vals]是一个列表解析,将self.vals中得元素转换成字符,再用join拼接成一个字符串。
(3)剩下的"{" +,你应该知道是什么作用了。

这个return语句的作用就是将self.vals列表的元素转换成字符,拼接成类似这样 '{a,b,c}'的字符串。

return '{' + ','[str(e) for e in self.vals] + '}' 这句代码是错的
1,','[str(e) for e in self.vals],是不是在','和[str(e) for e in self.vals]中间掉了符号;
2,字符串不能和list相加。

猜想:应该是想这么写的 "{" + ','.join([str(e) for e in self.vals]) + "}"
建议你把self.vals的值print出来,然后再看下

百度一下,列表解析

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题