python - 如何改写代码更优雅

标签 python arrays list

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

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

我想知道是否有更优雅、更有效的方法来做同样的事情。一些想法?

最佳答案

这是一个使用更少代码并且可能更高效的方法,因为它只是在不调用 swapaxes 的情况下遍历 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

关于python - 如何改写代码更优雅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6574692/

相关文章:

python - 在 Pandas 中,根据不同模式选择多列的惯用方式是什么?

python - 我在机器人框架中得到了元组列表而不是字典

java - 数组不同部分的两个最大值的最大绝对差?

javascript - 我如何告诉 Observable 我的数组已完成

c# - 从字符串列表中选择随机字符串的更好方法

java - 从 Iterable 创建 List 时使用哪个实现

python - 从 Microsoft Word 获取拼写错误的单词

javascript - 将显示的数组逗号替换为换行符

python - 从 Python 中的频率字典构建列表列表

Python 矩阵 - 将矩阵限制在前 20 名