数字对列表需要乘法和加法策略

2024-06-25 23:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数字对列表如下:

my_list = [(0,9),(1,5),(0,12),(2,8),(1,13),(2,17)]

我需要基于每对的第一个数字的点积作为匹配密钥。换句话说,我将912相乘,因为0匹配。我将把这个放在一边,并添加下一个匹配的乘积(5 * 13,因为它们在值1上匹配)。你知道吗

我有一个丑陋的解决方案,它要求我知道列表的长度:

print my_list
dotproduct = 0
i = 0
for ml1 in my_list:

  for ml2 in my_list:
      if ml1[0] == ml2[0] and ml1[1] != ml2[1] and i < 4:
        print 'multiply ',ml1[1] ,' and ', ml2[1]
        dotproduct += ml1[1] * ml2[1]
        print 'count = ', i
        i += 1
print dotproduct

只有当乘积的操作数不相等时,这种方法才有效。简言之,当集合的长度已知且乘积操作数不相同时,它可以工作。很虚弱。你知道吗

如果不是很明显的话,我是一个喜欢Python的人。你知道吗


Tags: andin列表forifmy密钥数字
1条回答
网友
1楼 · 发布于 2024-06-25 23:14:54

这可以通过^{}非常简单地完成:

from collections import defaultdict

out = defaultdict(lambda: 1)

for key, val in my_list:
    out[key] *= val
dotproduct = sum(out.values())

对于您的示例输入,这里给出了dotproduct == 309。你知道吗

相关问题 更多 >