我写了这个函数。输入和预期结果在文档字符串中指示。
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/