英文:
Math over list values of a dictionary with unlimited items
问题
我怎么样逐个循环遍历所有键的列表值,直到达到最后一个列表的数组值的末尾?每个键的所有列表都具有相同的长度。 我的意思是:
my_dict1 = {'c1': [10, 11, 12], 'c2': [100, 110, 120], 'c3': [200, 210, 220]}
my_dict2 = {'c1': 3, 'c2': 1, 'c3': 2}
我需要获得的结果是:
result = 0.5 * ([10 * 3 + 100 * 1 + 200 * 2] + [11 * 3 + 110 * 1 + 210 * 2] + [12 * 3 + 120 * 1 + 220 * 2])
我已经查看了 https://stackoverflow.com/questions/46550213/multiplying-the-values-of-dictionaries-with-different-keys 和 https://stackoverflow.com/questions/53078068/how-to-multiply-list-elements-in-dictionary,但它们在这里没有帮助。
以下代码只在两个字典具有相似键时有效。
dict1 = {2: [10, 11, 12], 2: [100, 110, 120]}
dict2 = {2: [100, 110, 120], 2: [100, 110, 120]}
result = {i: [x * y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}
print(result)
结果:
{2: [10000, 12100, 14400]}
我应该使用NumPy还是Pandas来处理它?在我的实际工作中,有一个具有未知键数的字典或数据帧。
英文:
How do I loop through all keys list values one by one until I reach the end of the last list's array value? All lists are the same length for each key.
I mean:
my_dict1 = {'c1': [10, 11, 12], 'c2': [100, 110, 120], 'c3': [200, 210, 220]}
my_dict2 = {'c1': 3, 'c2': 1, 'c3': 2}
The result I need to get is:
result = 0.5 * ([10 * 3 + 100 * 1 + 200 * 2] + [11 * 3 + 110 * 1 + 210 * 2] + [12 * 3 + 120 * 1 + 220 * 2])
I checked https://stackoverflow.com/questions/46550213/multiplying-the-values-of-dictionaries-with-different-keys and https://stackoverflow.com/questions/53078068/how-to-multiply-list-elements-in-dictionary but they did not come in handy here.
The following just worked when two dictionary have the similar keys.
dict1 = {2: [10, 11, 12], 2: [100, 110, 120]}
dict2 = {2: [100, 110, 120], 2: [100, 110, 120]}
result = {i :[x*y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}
print(result)
Result:
{2: [10000, 12100, 14400]}
Should I work by the NumPy or Pandas to handle it? In my real job there is a dictionary or a data frame with unknown number of keys.
答案1
得分: 0
一种方法只使用 zip
:
arr = []
for k, v in my_dict1.items():
c = my_dict2[k]
arr.append([i * c for i in v])
out = [sum(a)/2 for a in zip(*arr)]
或者使用 pandas
:
out = pd.DataFrame(my_dict1).mul(my_dict2).sum(axis=1).mul(0.5)
输出:
[265.0, 281.5, 298.0]
英文:
One way just using zip
:
arr = []
for k, v in my_dict1.items():
c = my_dict2[k]
arr.append([i * c for i in v])
out = [sum(a)/2 for a in zip(*arr)]
Or using pandas
:
out = pd.DataFrame(my_dict1).mul(my_dict2).sum(axis=1).mul(0.5)
Output:
[265.0, 281.5, 298.0]
答案2
得分: 0
如果你只想进行数学运算...
my_dict1 = {'c1': [10, 11, 12], 'c2': [100, 110, 120], 'c3': [200, 210, 220]}
my_dict2 = {'c1': 3, 'c2': 1, 'c3': 2}
result=0
for i in my_dict1:
for j in range(len(my_dict1[i])):
result+=my_dict1[i][j]*my_dict2[i]
result/=2
print(result)
英文:
If you just want to do the math...
my_dict1 = {'c1': [10, 11, 12], 'c2': [100, 110, 120], 'c3': [200, 210, 220]}
my_dict2 = {'c1': 3, 'c2': 1, 'c3': 2}
result=0
for i in my_dict1:
for j in range(len(my_dict1[i])):
result+=my_dict1[i][j]*my_dict2[i]
result/=2
print(result)
答案3
得分: 0
只返回翻译好的部分,不包括代码部分:
- "You must use the key from
my_dict1
to find the multiplier inmy dict2
." -> "您必须使用my_dict1
中的键来查找my_dict2
中的乘数。" - "From there on, you can just zip the lists and sum their items." -> "然后,您可以将列表进行压缩并对其项求和。"
- "Above gives as expected:" -> "上面的结果如预期:"
- "[265.0, 281.5, 298.0]" -> "[265.0, 281.5, 298.0]"
- "You could also build 2 numpy arrays for the same operation:" -> "您还可以构建两个NumPy数组执行相同的操作:"
- "arr1 = np.array(list(my_dict1.values()))" -> "arr1 = np.array(list(my_dict1.values()))"
- "arr2 = np.array([my_dict2[k] for k in my_dict1])" -> "arr2 = np.array([my_dict2[k] for k in my_dict1])"
- "Then:" -> "然后:"
- "np.sum(np.transpose(arr1) * arr2, axis=1)/2" -> "np.sum(np.transpose(arr1) * arr2, axis=1)/2"
- "gives as expected" -> "如预期给出"
- "array([265. , 281.5, 298. ])" -> "array([265. , 281.5, 298. ])"
英文:
You must use the key from my_dict1
to find the multiplier in my dict2
. From there on, you can just zip the lists and sum their items. It can be a plain Python inliner:
[sum(i)/2 for i in zip(*([i * my_dict2[k] for i in v]
for k, v in my_dict1.items()))]
Above gives as expected:
[265.0, 281.5, 298.0]
You could also build 2 numpy arrays for the same operation:
arr1 = np.array(list(my_dict1.values()))
arr2 = np.array([my_dict2[k] for k in my_dict1])
Then:
np.sum(np.transpose(arr1) * arr2, axis=1)/2
gives as expected
array([265. , 281.5, 298. ])
答案4
得分: 0
使用DataFrame、Numpy和纯Python似乎可以解决这个问题。根据Python的Ballesta的回答:
[sum(i)/2 for i in zip(*([i * my_dict2[k] for i in v] for k, v in my_dict1.items()))]
使用Ballesta的答案和Numpy:
arr1 = np.array(list(my_dict1.values()))
arr2 = np.array([my_dict2[k] for k in my_dict1])
np.sum(np.transpose(arr1) * arr2, axis=1)/2
或者使用Chris的答案和pandas:
out = pd.DataFrame(my_dict1).mul(my_dict2).sum(axis=1).mul(0.5)
使用DataFrame的更简单方式可能是:
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index() # 确保索引与行数匹配
for index, row in df.iterrows():
print((row['c1'] + row['c2']) / 2)
英文:
It seems here using the Dataframe, Numpy and just python this question can be solved.
As Ballesta have replied based on Python:
[sum(i)/2 for i in zip(*([i * my_dict2[k] for i in v]
for k, v in my_dict1.items()))]
Using Ballesta answer and Numpy:
arr1 = np.array(list(my_dict1.values()))
arr2 = np.array([my_dict2[k] for k in my_dict1])
np.sum(np.transpose(arr1) * arr2, axis=1)/2
Or using pandas as Chris has answerd:
out = pd.DataFrame(my_dict1).mul(my_dict2).sum(axis=1).mul(0.5)
A simpler way using the DataFrame could be:
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index() # make sure indexes pair with number of rows
for index, row in df.iterrows():
print((row['c1'] + row['c2'] )/ 2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论