循环求和和倍数

时间:2018-12-10 23:23:25

标签: python json

我试图弄清楚该如何做才能成功。希望你们能理解我为什么要尝试。

我有这个数据

names = "name: almog quantity: 1 status: none name: avraham quantity: 6 status: none name: asaf quantity: 12 status: none name: yossi quantity: 2 status: none name: mishel quantity: 3 status: none"

values_li={'almog':'1.11','asaf':'2.33','yossi':'3.21','avraham':'4.16','mishel':'12.91'}

for k,v in values_li.items():
        if k in names:
                amount = float(v)


print(amount)

现在,我有了每个字符串的总数...但是,如何将每个字符串乘以他的下一个数量字符串?例如: almog是1.11而他的数量是1 1.11 * 1 ..... 亚伯拉罕是4.16,他的数量是6 4.16 * 6 ..... 等等,然后获得所有这些值的总和。

谢谢,希望您能理解。

*编辑---

感谢所有帮助,但现在变得更加复杂...

一开始我有这段代码

names = "name: almog grams: 9 id:141 quantity: 1 status: none name: avraham grams: 3 id:146 quantity: 6 status: none name: asaf grams: 1 id:1241 quantity: 12 status: none name: yossi grams: 2 id:2141 quantity: 2 status: none name: mishel grams: 6 id:1641 quantity: 3 status: none"

values_li={'bar':'47.2','loren':'11.12','yossi':'3.21','avraham':'4.16','mishel':'12.91'}
for k,v in values_li.items():
    if k in names:
        amounts = float(v)

因此,只有在名称字符串中找到values_li之一时,它才会对金额进行求和。不,我不知道如何使用您创建的新代码来找到每个代码的数量并将其相乘。

基本上,我只想将values_li列表中的值之一与数量相乘,然后将它们总和为一个变量...

关于如何实现的任何想法?

2 个答案:

答案 0 :(得分:0)

You could use a regular expression to extract the names and quantities from the names string:

>>> re.findall(r"name: (\w+) quantity: (\d+)", names)
[('almog', '1'),
 ('avraham', '6'),
 ('asaf', '12'),
 ('yossi', '2'),
 ('mishel', '3')]

Use a dict comprehension to map names to quantities, and then use another dict comprehension to multiply those with the values to get the results:

>>> quantities = {name: float(quant) for name, quant in re.findall(r"name: (\w+) quantity: (\d+)", names)}
>>> {name: float(values_li[name]) * quantities[name] for name in values_li}
{'asaf': 27.96,
 'almog': 1.11,
 'yossi': 6.42,
 'avraham': 24.96,
 'mishel': 38.730000000000004}

This is assuming that the names string is always formatted in this way, and that both the names string and the values_li dict contain the same names. (If the latter is not the case, you can use ... for name in values_li if name in quantities}.)

For your more complex example, use this regex: r"name: (\w+).*? quantity: (\d+)". The .*? will match a minimum number of characters between the two fields. This will allow for other attributes between name and quantity, but it still assumes that name is first.

答案 1 :(得分:0)

您可以使用re.findall来解析names并将其转换为名称到数量的映射dict,然后使用dict理解生成所需的名称到数量的映射:

import re
quantities = dict(re.findall(r'\bname: (\S+) quantity: (\d+)', names))
amounts = {k: float(v) * int(quantities[k]) for k, v in values_li.items()}

amounts变为:

{'almog': 1.11, 'asaf': 27.96, 'yossi': 6.42, 'avraham': 24.96, 'mishel': 38.730000000000004}