剛才那個代碼有誤,我把全部貼出來
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]) + "}"
初學(xué),return后面這一句依然沒看懂 .join在這里是method嗎, 這個格式是怎么回事
3 回答

慕虎7371278
TA貢獻1802條經(jīng)驗 獲得超4個贊
(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中得元素轉(zhuǎn)換成字符,再用join拼接成一個字符串。
(3)剩下的"{" +,你應(yīng)該知道是什么作用了。
這個return語句的作用就是將self.vals列表的元素轉(zhuǎn)換成字符,拼接成類似這樣 '{a,b,c}'的字符串。

慕村225694
TA貢獻1880條經(jīng)驗 獲得超4個贊
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相加。
猜想:應(yīng)該是想這么寫的 "{" + ','.join([str(e) for e in self.vals]) + "}"
建議你把self.vals的值print出來,然后再看下
添加回答
舉報
0/150
提交
取消