简体   繁体   English

如何比较 python 中列表/数组/字典中的对应元素

[英]How to compare corresponding elements in list/array/dict in python

Suppose you have two lists (or any type of grouping, it doesn't matter which one) containing variables that represent milk, eggs, and flour.假设您有两个包含表示牛奶、鸡蛋和面粉的变量的列表(或任何类型的分组,无论哪一个都没有关系)。 For instance:例如:

have(milk, eggs, flour)有(牛奶、鸡蛋、面粉)

and

need(milk, eggs, flour)需要(牛奶、鸡蛋、面粉)

How might you go about determining whether each element >=, ==, or <= its counterpart in the other list so that you can return some indication as to whether there is or is not enough of each ingredient to make a proverbial cake or if there is enough to make more than one?您如何 go 确定每个元素是否 >=、== 或 <= 在另一个列表中的对应项,以便您可以返回一些指示,说明每种成分是否足以制作众所周知的蛋糕,或者是否有足够多的吗?

I'd really prefer not to write War and Peace for the sake of 3 comparisons.为了3个比较,我真的不想写战争与和平。 Any help is appreciated.任何帮助表示赞赏。

You could use dictionaries.你可以使用字典。 For instance:例如:

have = {"milk": 2, "eggs": 3, "flour": 0.5}
need = {"milk": 1, "eggs": 5, "flour": 2.5}
ingredients = {i:"Yes" if have[i] >= need[i] else "No" for i in have.keys()}

Output: Output:

print(ingredients)
{'milk': 'Yes', 'eggs': 'No', 'flour': 'No'}

If you want a function that tells you how many cakes you can do with the ingredients you have, you can use the following:如果您想要一个 function 告诉您可以用您拥有的原料制作多少个蛋糕,您可以使用以下内容:

def how_many(need, have):
    results = {i:have[i]//need[i] for i in have.keys()}
    return min(results.values())

If the a list of quantities that you need to compare, you can use a one-liner list comprehension (can only compare ==, >, < else it they will be overlapping operations if you use >= and <= and ==) -如果您需要比较的数量列表,您可以使用单行列表理解(只能比较 ==、>、< 否则如果您使用 >= 和 <= 和 ==,它们将是重叠操作) -

milk_have = 10
eggs_have = 20
flour_have = 30

milk_need = 10
eggs_need = 25
flour_need = 3

have = [milk_have, eggs_have, flour_have]
need = [milk_need, eggs_need, flour_need]

['==' if i[0]==i[1] else '>' if i[0]>i[1] else '<' for i in zip(have, need)]
['==', '<', '>']

Asssuming input as the following假设输入如下

milk=200
eggs=10
flour=1000

milk_reqd=100
eggs_reqd=5
flour_reqd=2000

have=[milk, eggs, flour]
need=[milk_reqd, eggs_reqd, flour_reqd]

Solution解决方案

import numpy as np
have=np.array(have)
need=np.array(need)

Now you can perform all operations like现在您可以执行所有操作,例如

need>have

Or或者

need<=have

Or或者

need-have

To get the number of cakes that can be made获取可以制作的蛋糕数量

n_cakes=int(min(have/need))
have = ('milk', 'eggs', 'flour',"k")
need = ('milk', 'eggs', 'flour',"l")
incredients = {}
for i in range(len(have)):
   count = 0 
   if have[i] == need[i]:
      count +=1
   incredients[have[i]] = count

output: {'eggs': 1, 'flour': 1, 'k': 0, 'milk': 1} output: {'eggs': 1, 'flour': 1, 'k': 0, 'milk': 1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM