Python 追加当前行数的总和
这是我的密码:Python 追加当前行数的总和,python,python-3.x,Python,Python 3.x,这是我的密码: def dictListSum(dictionary): temporary_list = [] final_list = [] for (key, value) in sorted(dictionary.items()): temporary_list.append(value[0:]) nRows = len(temporary_list) nCols = len(temporary_list[0]) fo
def dictListSum(dictionary):
temporary_list = []
final_list = []
for (key, value) in sorted(dictionary.items()):
temporary_list.append(value[0:])
nRows = len(temporary_list)
nCols = len(temporary_list[0])
for row in range(0, nRows-1):
for col in range(0, nCols):
final_list.append(temporary_list[row][col] + temporary_list[row + 1][col])
return final_list
我在处理这一行时遇到问题:
final_list.append(temporary_list[row][col] + temporary_list[row + 1][col])
以下是我希望从用户的字典输入中得到的格式:
a = {'A': [3, 11, 2], 'B': [5, 2, 0]}
现在,如果用户的字典只有两个键,那么代码可以正常运行。当用户输入以下内容时,我的问题开始出现:
a = {'A':[4, 5, 2, 5, 6, 3], 'B': [4, 5, 6, 2, 4, 6], 'C': [1, 1, 1, 1, 1, 1,], 'D': [2, 2, 2, 2, 2, 2]}
final_list.append(temporary_list[row][col] + temporary_list[row + 1][col] temporary_list[row + 2][col] temporary_list[row + 3][col])
如果是这种情况,那么我的麻烦代码行必须如下所示:
a = {'A':[4, 5, 2, 5, 6, 3], 'B': [4, 5, 6, 2, 4, 6], 'C': [1, 1, 1, 1, 1, 1,], 'D': [2, 2, 2, 2, 2, 2]}
final_list.append(temporary_list[row][col] + temporary_list[row + 1][col] temporary_list[row + 2][col] temporary_list[row + 3][col])
那么,我如何才能将所有行(当前列表)以顺序格式添加到一起呢请记住,用户可以创建他/她想要的任意多个密钥,只要它们具有相同的长度并采用列表格式。
可能错误的输出示例(使用后一个字典):
应该发生什么:
dictListSum(a)
[11, 13, 11, 10, 13, 12]
考虑这一点的一种方法是:将字典的值视为表中的行,然后沿列求和。i、 e.将其转换为:
[4, 5, 2, 5, 6, 3],
[4, 5, 6, 2, 4, 6],
[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2]
为此:
[4, 4, 1, 2],
[5, 5, 1, 2],
[6, 2, 1, 2],
[2, 5, 1, 2],
[4, 6, 1, 2],
[6, 3, 1, 2]
…然后对列表求和。为实现这一目标:
[sum(lst) for lst in zip(*a.values())]
是一种基本上等同于“转置”一个“矩阵”的模式;然后,我们只需沿着每个“行”(
lst
)求和。思考这个问题的一种方法是:将字典中的值视为表中的行,然后沿着列求和。i、 e.将其转换为:
[4, 5, 2, 5, 6, 3],
[4, 5, 6, 2, 4, 6],
[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2]
为此:
[4, 4, 1, 2],
[5, 5, 1, 2],
[6, 2, 1, 2],
[2, 5, 1, 2],
[4, 6, 1, 2],
[6, 3, 1, 2]
…然后对列表求和。为实现这一目标:
[sum(lst) for lst in zip(*a.values())]
是一种基本上等同于“转置”一个“矩阵”的模式;然后,我们沿着每个“行”(
lst
)求和。zip(*iterables)函数——这完美地解决了我的问题。不过,我必须问:有没有办法以顺序格式(针对我的原始代码)完成你发布的答案,或者需要我的原始函数为允许的键数设置一个值?@TZK203我不确定你所说的“顺序”是什么意思。你的意思是什么?这里有一个我想要的例子。因此,假设必须至少有2个键值:如果有2个键值:(临时列表[行][col]+临时列表[行+1][col])如果有3个键值:(临时列表[行][col]+临时列表[行+1][col]+临时列表[行+2][col col]),等等。@TZK203我的意思是,你可以把它放在一个for循环中——创建一个临时变量temp=0
,然后为范围内的i(len(临时列表)):temp+=temporary\u list[row+i][col]
。zip(*iterables)函数——这完美地解决了我的问题。不过,我必须问:有没有办法以顺序格式(针对我的原始代码)完成你发布的答案,或者需要我的原始函数为允许的键数设置一个值?@TZK203我不确定你所说的“顺序”是什么意思。你的意思是什么?这里有一个我想要的例子。因此,假设必须至少有2个键值:如果有2个键值:(临时列表[行][col]+临时列表[行+1][col])如果有3个键值:(临时列表[行][col]+临时列表[行+1][col]+临时列表[行+2][col col]),等等。@TZK203我的意思是,您可以将其放入for循环中—创建一个临时变量temp=0
,然后为范围内的i(len(临时列表)):temp+=temporary\u list[row+i][col]。