Python 将类的实例分解为列表,或者:对类变量求和的更好方法?
这是我一直在做的一个项目的一部分。我很难用我能写的东西来合成心理上的伪代码,这主要是因为我个人对东西如何工作的误解 我正在使用以下类跟踪一个虚拟水果摊的库存:Python 将类的实例分解为列表,或者:对类变量求和的更好方法?,python,class,Python,Class,这是我一直在做的一个项目的一部分。我很难用我能写的东西来合成心理上的伪代码,这主要是因为我个人对东西如何工作的误解 我正在使用以下类跟踪一个虚拟水果摊的库存: class Fruit(object) def __init__(self,name,qty,price) self.color = str(color) self.qty = int(qty) self.price = float(price) def getName(s
class Fruit(object)
def __init__(self,name,qty,price)
self.color = str(color)
self.qty = int(qty)
self.price = float(price)
def getName(self): return self.color
def getQty(self): return self.qty
def getPrice(self): return self.price
def description(self): return self.color,self.qty,self.price
此类中的对象最终会作为字典键的值导入。每个键可以有多个值,存储在一个列表中,这样当打印字典时,它会返回如下内容(为了可读性,使用换行符:)
我现在试图得到我想象中的水果架上所有水果的总和。我最初的想法是将每个值作为一个列表,在列表中迭代,直到找到一个整数,将整数乘以它后面索引中的浮点数,然后将该数量添加到一个有运行总数的变量中;然后继续寻找另一个整数。如果列表“樱桃”的“索引1”不是(红色,5,5.99)而不是(2),那么这将非常有效
所以,有几个问题
提前谢谢。我已经和这个问题的各个部分斗争了一周。你要找的词是。这些“附加说明”是 Python的主要优势之一是它用于迭代列表的紧凑语法。您可以在一行中计算每个水果的价格总和:
>>> fruit = [("Red", 10, 0.99), ("Green", 9, 0.69)]
>>> sum(qty * price for color, qty, price in fruit)
16.11
分解它,sum()
中的内容称为a对于水果中的颜色、数量、价格
迭代水果
并将元组解压为三个命名变量。然后,这些变量可以在的左侧使用。对于水果
列表中的每个元组,生成器表达式计算数量*价格
如果将此表达式放在方括号内,它将成为一个表达式,并允许您查看计算值
>>> [qty * price for color, qty, price in fruit]
[9.9, 6.209999999999999]
我会首先抛弃returnFoo
方法,因为它比键入apple要短。price
:
class Fruit(object)
def __init__(self, name, qty, price)
self.color = str(color)
self.qty = int(qty)
self.price = float(price)
如果不接受任意输入,如qty='100'
,则也不需要进行类型转换:
class Fruit(object)
def __init__(self, name, qty, price)
self.color = color
self.qty = qty
self.price = price
剩下的是一个只存储值的类。在这种情况下,我会使用字典:
fruit = {
'color': 'red',
'qty': 1000,
'price': 1.99
}
要计算成本,首先需要水果:
fruits = [{
'color': 'red',
'qty': 1000,
'price': 1.99
}, {
'color': 'blue',
'qty': 100,
'price': 15.99
}, {
'color': 'orange',
'qty': 10,
'price': 5.99
}]
然后您可以使用for
循环:
total = 0
for fruit in fruits:
total += fruit['qty'] * fruit['price']
可以使用sum
和生成器表达式进一步简化:
total = sum(fruit['price'] * fruit['qty'] for fruit in fruits)
另一种选择是使用水果摊
类和您原来的水果
类:
class FruitStand(object):
def __init__(self, fruits=None):
self.fruits = fruits or []
def totalCost(self):
return sum(fruit.price * fruit.qty for fruit in self.fruits)
假设字典是这样的:
fruit_stand = {
"Lemon": [(Yellow, 5, 2.99)],
"Apple": [(Red, 10, 0.99), (Green, 9, 0.69)],
"Cherry": [(White, 2, 5.99),(Red, 5, 5.99)]
}
实际上,您可以迭代字典以获取其键:
for fruit_name in fruit_stand:
print fruit_name
# Lemon
# Apple
# Cherry
# NOTE: Order not guaranteed
# Cherry, Lemon, Apple are equally likely
然后,您可以使用字典的items
方法获取键
,值
对的元组(您称之为“括号”):
for fruit_name, fruits in fruit_stand.items():
print fruit_name, "=>", fruits
# Lemon => [(Yellow, 5, 2.99)]
# Apple => [(Red, 10, 0.99), (Green, 9, 0.69)]
# Cherry => [(White, 2, 5.99),(Red, 5, 5.99)]
列表
s(即括号中的[]
)也可用于:
for fruit in [(White, 2, 5.99),(Red, 5, 5.99)]:
print fruit
# (White, 2, 5.99)
# (Red, 5, 5.99)
因此,我们可以使用每个水果
列表来访问我们的元组
:
for fruit_name, fruit_list in fruit_stand.items():
# Ignore fruit_name and iterate over the fruits in fruit_list
for fruit in fruit_list:
print fruit
正如我们在项中看到的那样,我们可以将元组解压为多个值:
x, y = (1, 2)
print x
print y
# 1
# 2
因此,我们可以将每个水果
分解为其组成部分:
for fruit_name, fruit_list in fruit_stand.items():
# Ignore fruit_name and iterate over the fruits in fruit_list
for color, quantity, cost in fruit_list:
print color, quantity, cost
然后得到总数并不难:
# We need to store our value somewhere
total_value = 0
for fruit_name, fruit_list in fruit_stand.items():
# Ignore fruit_name and iterate over the fruits in fruit_list
for color, quantity, cost in fruit_list:
total_value += (quantity * cost)
print total_value
尽管如此,还有更清晰的做事方式:
您可以使用列表理解来简化循环的:
for fruit_name in fruit_stand
operation(fruit_name)
可以翻译为以下列表:
[operation(fruit_name) for fruit_name in fruit_stand]
因此,我们可以将嵌套的for
循环转换为:
sum([cost * quantity \ # Final operation goes in front
for _, fruits in fruit_stand.items() \
for _, cost, quantity in fruits])
因为我们实际上不需要这个列表,所以我们可以去掉它,Python将为我们创建一个生成器:
sum(cost * quantity \ # Note the missing []
for _, fruits in fruit_stand.items() \
for _, cost, quantity in fruits)
您可以在水果中添加\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu(但是您可能想创建一个中间数据结构来实现这一点,比如说Basket
,这样Fruit
就不必担心quantity
,因为它实际上不属于Fruit
,除非Fruit
的任何实例都具有内在数量1。我省略了这个o的代码。)因为这个答案已经太长了
顺便说一句,你所说的插入语被称为元组;-)谢谢你-也谢谢你提醒我我所说的插入语的正确名称。我已经尝试了几个版本。我正在尝试几种方法来定义这个列表,“水果”,通过引入我想要的列表-最近“对于水果中的键:values=Fruit.get(key)\n total=sum(数量*颜色、数量、水果中的价格)。此返回的ValueError-太多值无法解包。这意味着“您正在做的事情很愚蠢,“但我不确定我是否能想出更好的方法来引入这些值。我的想法是否正确?谢谢。项目规范要求对水果使用一个类,而不仅仅是一个字典,所以我选择你的第二个选项。我试着将其称为(使用;换行符)“fruity=水果摊;total=fruity.totalCost();print total”。我得到的是错误“unbound meth”
sum(cost * quantity \ # Note the missing []
for _, fruits in fruit_stand.items() \
for _, cost, quantity in fruits)