Python 3,列出理解,范围以及如何与外部变量进行比较 [英] Python 3, list comprehensions, scope and how to compare against external variables

查看:73
本文介绍了Python 3,列出理解,范围以及如何与外部变量进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示库存项目及其价值的类:

I have a class representing items of stock and their value:

class stock:
    def __init__(self, stockName, stockType, value):
        self.name = stockName
        self.type = stockType
        self.value = value

我有大量的库存,因此我列出了库存对象清单,从中可以访问单个项目的值,例如stockList[12].value

I have loads of stock so I make a list of stock objects from which I can access the value of individual items e.g stockList[12].value

我想累加所有属于衬衫"的库存物品的价值.以下工作正常:

I want to add up the value of all stock items which are 'shirts'. The following works fine:

shirtValue = sum([s.value for s in stockList if s.value == 'shirt'])

好的,很好.但是现在我有了一个stockType的列表,希望对与stockType列表中特定条目匹配的项的值求和,例如:

OK, fine. But now I have a list of stockType and wish to sum the value of items which match a particular entry in the stockType list e.g.:

stockTypeValue[0] = sum([s.value for s in stockList if s.value == stockType[0]])

其中stockType[0] = 'shirt'这不起作用.我知道为什么-这是因为在Python 3中列表理解具有自己的范围(请在此处查看详细答案:

where stockType[0] = 'shirt'This doesn't work. I know Why - it is because in Python 3 list comprehensions have their own scope (See detailed answer here: Accessing class variables from a list comprehension in the class definition )

我的问题是:我编写的代码(我认为可以在Python 2中运行)看起来很棒,它干净,易于理解,并且未经训练的人看起来很pythonic.

My question is this: The code I have written, which I think would work in Python 2 looks great, it is clean, easy to understand, and to the untrained eye looks very pythonic.

但是我无法弄清楚如何在Python 3中以一种不错的pythonic方式做同样的事情.我要回到大循环结构上.

But I can't figure out how to do the same thing in a nice pythonic way in Python 3. I'm going back to big loop structures.

在Python 3中执行此操作的最佳方法是什么?

What is the best way to do this in Python 3?

*编辑* 错误消息:

以下是我要执行的操作的示例:

Here is an example of what I am trying to do:

stockList=[]
stockList.append(stock('product A', 'shirt', 53.2))
stockList.append(stock('product B', 'hat', 20.2))

sum([s.value for s in stockList if s.type=='shirt'])

输出:

Out[5]: 53.3

但是如果我将'shirt'放到变量中:

But if I put 'shirt' into a variable:

stockType = 'shirt'
sum([s.value for s in stockList if s.type==stockType])

输出:

Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "<console>", line 1, in <listcomp>
NameError: name 'stockType' is not defined

推荐答案

这不起作用.我知道为什么-这是因为在Python 3中列表理解具有自己的范围(请在此处查看详细答案:实际上是不正确的.我的意思是,当然,这个问题的答案是正确的,但事实并非如此.该问题仅与定义时在类主体中发生的表达式有关.如果您是在一个方法中,那么根本没有问题.

That’s actually not true. I mean, of course that answer in that question is correct but that’s not what is happening here. That question is only relevant for expressions that happen in the class body at definition time. If you are e.g. within a method though then there is no problem at all.

但是,可能失败的原因(可能是因为您没有提供错误消息)是目标列表stockTypeValue未初始化.

However, what likely fails ("likely" because you didn’t supply the error message), is that the target list stockTypeValue isn’t initialized.

>>> stockTypeValue[0] = 'something'
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    stockTypeValue[0] = 'something'
NameError: name 'stockTypeValue' is not defined

所以我们现在可以定义它并分配一个空列表.但列表仍然为空:

So we can define it now and assign an empty list; but the list is still empty:

>>> stockTypeValue = []
>>> stockTypeValue[0] = 'something'
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    stockTypeValue[0] = 'something'
IndexError: list assignment index out of range

相反,您必须将结果附加到空白列表中

Instead, you would have to append the result to the empty list:

>>> stockTypeValue.append('something')
>>> stockTypeValue[0]
'something'


重播您的示例:


Replaying your example:

>>> stockList = []
>>> stockList.append(stock('product A', 'shirt', 53.2))
>>> stockList.append(stock('product B', 'hat', 20.2))
>>> sum([s.value for s in stockList if s.type == 'shirt'])
53.2
>>> stockType = 'shirt'
>>> sum([s.value for s in stockList if s.type == stockType])
53.2

这篇关于Python 3,列出理解,范围以及如何与外部变量进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆