Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用iterable中包含的每次执行的参数多次高效地执行方法_Python_Loops_List Comprehension - Fatal编程技术网

Python 使用iterable中包含的每次执行的参数多次高效地执行方法

Python 使用iterable中包含的每次执行的参数多次高效地执行方法,python,loops,list-comprehension,Python,Loops,List Comprehension,我有一个方法,我需要执行多次,然后读取最终结果。该对象如下所示: class BlackBox(object): def __init__(self): self._x = 0 def do_unknown_caulculation(self, word): self._x += len(word) def get_result(self): return self._x 我想到了两种做这项工作的方法。在循环中并通过使用列表理解: def loopit

我有一个方法,我需要执行多次,然后读取最终结果。该对象如下所示:

class BlackBox(object):

  def __init__(self):
    self._x = 0

  def do_unknown_caulculation(self, word):
    self._x += len(word)

  def get_result(self):
    return self._x
我想到了两种做这项工作的方法。在循环中并通过使用列表理解:

def loopit(words, aggregator):
  for word in words:
    aggregator.do_unknown_caulculation(word)
  return aggregator.get_result()


def comprehendit(words, aggregator):
  [aggregator.do_unknown_caulculation(word) for word in words]
  return aggregator.get_result()


words = ['I', 'need', 'to', 'aggregate', 'this']

print (loopit(words, BlackBox()), comprehendit(words, BlackBox()))
我发现列表理解版稍微快一点,但我不认为这是一种正确的方法。我似乎误用了预期的功能,从线程安全的角度来看,我不知道这样做是否安全


什么是我想要的高效的python方式?

我会选择
loopit()
,因为
comprehendit()
构建了一个列表,其中可能有许多引用我们不需要的None对象。我不认为总是有一种更像python的方式来做事情。

我会选择
loopit()
,因为
comprehendit()
构建了一个列表,其中包含对我们不需要的None对象的潜在多个引用。我不认为总是有一种更像Python的方式来做事情。

您可以在Python 3.x中使用map或在Python 2.7.x中使用imap(在这种情况下,您必须从itertools import imap导入
)-

def usingMap(单词、聚合器):
列表(映射(aggregator.do_unknown_caulculation,words))

return aggregator.get_result()

您可以在Python 3.x中使用map或在Python 2.7.x中使用imap(在这种情况下,您必须从itertools导入imap
)-

def usingMap(单词、聚合器):
列表(映射(aggregator.do_unknown_caulculation,words))

return aggregator.get_result()

如果将其转换为
列表,为什么要使用
imap
?此外,这与列表理解没有多大区别。如果你把它变成一个
列表,为什么要使用
imap
?而且,这与列表理解没有什么不同。