[英]Pythonic way using list comprehension
I have this code that I know can be much more efficient.... 我知道这段代码可以提高效率。...
return_list = []
for attribute in attributes:
if attribute['internalname'] in attributenames:
attr = Attribute();
attr.name = attribute['internalname']
attr.value = attribute['value']
return_list.append(attr);
return return_list
I could have easily done list comprehension but since there is an object creation attr=Attributes()
, I don't know how would I handle that? 我本来可以很容易地完成列表理解,但是由于有一个对象创建
attr=Attributes()
,我不知道该如何处理?
Make Attribute()
take the name and value as arguments: 使
Attribute()
以名称和值作为参数:
return [Attribute(attr['internalname'], attr['value'])
for attr in attributes if attr['internalname'] in attributenames]
You could make it accept keyword arguments instead if you need to support various attributes instead: 如果您需要支持各种属性,则可以改为接受关键字参数:
return [Attribute(name=attr['internalname'], value=attr['value'])
for attr in attributes if attr['internalname'] in attributenames]
If neither is an option, make a function to create the Attribute
object with a name
and value
attribute: 如果两者都不是选项,请创建一个函数以创建具有
name
和value
属性的Attribute
对象:
def create_attribute(name, value):
attr = Attribute()
attr.name = name
attr.value = value
return attr
return [create_attribute(attr['internalname'], attr['value'])
for attr in attributes if attr['internalname'] in attributenames]
Is there an __init__
method for Attribute
that takes named parameters? 是否有
__init__
的Attribute
方法采用命名参数? If so, you could do something like 如果是这样,您可以做类似的事情
return_list = [Attribute(name=attribute['internalname'], value=attribute['value']) for attribute in attributes if attribute['internalname'] in attributenames]
This is meant as a comment, posting as an answer because the comment system is not suited for posting code samples. 因为注释系统不适用于发布代码样本,所以这意味着作为注释,作为答案发布。 There are two good answers using list comprehensions and I want to complement talking about generators and generator expressions.
使用列表推导有两个很好的答案,我想补充有关生成器和生成器表达式的讨论。
While a list comprehension is shorter than your function, it may also be less readable. 虽然列表理解比您的函数要短,但它的可读性也可能较低。 An alternative is using generators:
一种替代方法是使用生成器:
def make_attributes(attributes, attributenames):
for attribute in attributes:
if attribute['internalname'] in attributenames:
attr = Attribute();
attr.name = attribute['internalname']
attr.value = attribute['value']
yield attr
There is also generator expressions (use these in place of list comprehensions where you don't really need a real list, for example, when you are just iterating over the result): 还有生成器表达式(例如,当您仅迭代结果时,可以使用这些表达式代替列表推导,在这些列表中您不需要真正的列表):
# borrowing create_attribute from Martijn Pieters
return (
create_attribute(attr['internalname'], attr['value'])
for attr in attributes
if attr['internalname'] in attributenames
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.