玩蛇网提供最新Python编程技术信息以及Python资源下载!

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

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

百度一下,列表解析

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd18439.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年06月15日 - 09时41分38秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules