【问题标题】:How to rewrite the code more elegant如何更优雅地重写代码
【发布时间】:2011-07-04 17:57:09
【问题描述】:

我写了这个函数。文档字符串中指明了输入和预期结果。

def summarize_significance(sign_list):
    """Summarizes a series of individual significance data in a list of ocurrences.

    For a group of p.e. 5 measurements and two diferent states, the input data
    has the form:

    sign_list = [[-1, 1],
                 [0, 1],
                 [0, 0],
                 [0,-1],
                 [0,-1]]

    where -1, 0, 1  indicates decrease, no change or increase respectively.
    The result is a list of 3 items lists indicating how many measurements
    decrease, do not change or increase (as list items 0,1,2 respectively) for each state:

    returns: [[1, 4, 0], [2, 1, 2]]

    """
    swaped = numpy.swapaxes(sign_list, 0, 1)

    summary = []
    for row in swaped:
        mydd = defaultdict(int)
        for item in row:
            mydd[item] += 1
        summary.append([mydd.get(-1, 0), mydd.get(0, 0), mydd.get(1, 0)])

    return summary

我想知道是否有更优雅、更有效的方式来做同样的事情。有什么想法吗?

【问题讨论】:

  • 返回的例子有错误:一定是returns: [[1, 4, 0], [2, 1, 2] ]

标签: python arrays list


【解决方案1】:

这是一个使用更少代码并且可能更高效的一个,因为它只迭代一次 sign_list 而不调用交换轴,并且不构建一堆字典。

summary = [[0,0,0] for _ in sign_list[0]]

for row in sign_list:
  for index,sign in enumerate(row):
    summary[index][sign+1] += 1
return summary

【讨论】:

  • 好收获。索引是我们要增加的摘要行,符号+1 是列。这是一个可爱的黑客。
  • 您不需要使用range(len(...)),因为您实际上并不关心值是什么。
  • 实际上,我刚刚登录以更改它。
【解决方案2】:

不,只是更复杂的方法。

import itertools

def summarize_significance(sign_list):
  res = []
  for s in zip(*sign_list):
    d = dict((x[0], len(list(x[1]))) for x in itertools.groupby(sorted(s)))
    res.append([d.get(x, 0) for x in (-1, 0, 1)])
  return res

【讨论】:

  • 感谢 Ignacio,实际上更复杂,但您总是提供学习新东西的机会 :-)
【解决方案3】:

对于初学者,你可以这样做:

swapped = numpy.swapaxes(sign_list, 0, 1)
for row in swapped:
  mydd = {-1:0, 0:0, 1:0}
  for item in row:
     mydd[item] += 1
  summary.append([mydd[-1], mydd[0], mydd[1])
return summary

【讨论】:

  • 您可以将其保留为defaultdict(int),因为int 的默认值为0
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
相关资源
最近更新 更多