[英]Python: List of tuples: compare all tuples and retrive tuples where the elements of tuples are not equal to any other tuple
[英]Compare Tuple with a List of Tuples
我必须将元组与元组列表进行比较,如果整数小于列表中的任何元组,则返回 True。 就像如果我有superM ("Tomato",10,5) [("Potato",5,6),("Orange",11,6)]
将返回 True 因为单独元组中的整数 ("Tomate", 10,5) 比列表中的元组 ("Orange",11,6) 小,但是如果我有superM ("Melon",10,6) [("Potato",5,6),("Orange",11,6)]
将返回 False。
我试试这个
superM :: (String, Int, Int) -> [(String, Int, Int)] -> Bool
superM (s,a,b) ((_,c,d):xs)
| a < c && b < d = True
|otherwise = superM (s,a,b) xs
但是当它假设返回 False 时不起作用,我不知道为什么?
注意:字符串与此问题无关,我必须忽略它。
您没有为空列表定义 basecase。 所以如果没有元素匹配,最终列表将被耗尽,然后空列表将不匹配。 因此,您可以为空列表添加规则:
superM :: (String, Int, Int) -> [(String, Int, Int)] -> Bool
superM _ [] = False
superM (s,a,b) ((_,c,d):xs)
| a < c && b < d = True
|otherwise = superM (s,a,b) xs
我们可以利用逻辑或摆脱守卫:
superM :: (String, Int, Int) -> [(String, Int, Int)] -> Bool
superM _ [] = False
superM (s,a,b) ((_,c,d):xs) = a < c && b < d || superM (s,a,b) xs
但我们也可以使用any :: Foldable f => (a -> Bool) -> fa -> Bool
函数来让它与任何Foldable
工作:
superM :: (Foldable f, Ord x, Ord y) => (a, x, y) -> f (b, x, y) -> Bool
superM (_, a, b) = any p
where p (_, c, d) = a < c && b < d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.