python如何使这个代码更pythonic?

时间:2015-04-13 21:08:35

标签: python

所以我从麻省理工学院的“计算机科学与编程导论”讲座18中得到了这段代码。代码很少遵循pythonic风格。看看这个

class Item(object):

def __init__(self, n, v, w):
    self.name = n
    self.value = float(v)
    self.weight = float(w)

def getName(self):
    return self.name

def getValue(self):
    return self.value

def getWeight(self):
    return self.weight

def __str__(self):
    result = '<' + self.name + ', ' + str(self.value) + ', '\
             + str(self.weight) + '>'
    return result



def buildItems():
    names = ['clock', 'painting', 'radio', 'vase', 'book',
             'computer']
    vals = [175,90,20,50,10,200]
    weights = [10,9,4,2,1,20]
    Items = []
    #for i in range(len(vals)):
    #    Items.append(Item(names[i], vals[i], weights[i]))

    return Items

如何将函数的注释代码更改为pythonic代码?

我就这样做了:

for tup in zip(names, vals, weights):
            name, value, weight = tup
            Items.append(Item(name, value, weight))

还有其他方式吗?

编辑:Lec 18 | MIT 6.00SC Introduction to Computer Science and Programming, Spring 2011

2 个答案:

答案 0 :(得分:6)

Items = list(map(Item,zip(names,vals,weights)))

可能?

Items = [Item(*vals) for vals in zip(names,vals,weights)]

[编辑]不幸的是在考虑之后第一个例子将无法工作,因为它将所有3个参数作为一个元组传递而不解包...你可能需要更改Item的init函数以接受元组或使用lambda

Items = list(map(lambda a:Item(*a),zip(names,vals,weights)))

答案 1 :(得分:4)

这更短:

Items = [Item(name,value,weight) for name,value,weight in zip(names,vals,weights)]