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吗, 这个格式是怎么回事

return python

Yeah半瘦人 9 years, 6 months ago

百度一下,列表解析

复仇的黑百合 answered 9 years, 6 months ago

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出来,然后再看下

二次元信徒 answered 9 years, 6 months ago

(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}'的字符串。

真夏夜D中國夢 answered 9 years, 6 months ago

Your Answer