haskell - 列表中元素的长度
问题描述
假设我有列表 ["foo", "bar", "othercoolword"],我想知道每个元素的长度。我会做
map length ["foo", "bar", "othercoolword"]
然后它返回 [3,3,13]。但是,如果我在列表中有一个列表,例如
[["f","bee","oba"],["aloo","d","e"],["xnx","y","z"]]
我希望它返回 [[1,3,3],[4,1,1],[3,1,1]]。然后对该列表中的每个列表取最大值。这会给我[3,4,3]。
长话短说:我对列表中的这些列表感到困惑。有没有一种简单的方法可以做到这一点?
解决方案
是的,很简单。观察
map length ["foo", "bar", "othercoolword"]
=>
[3 , 3 , 13 ]
map length [["f","bee","oba"],["aloo","d","e"],["xnx","y","z","w"]]
=>
[3 ,3 ,4 ]
map length ["f","bee","oba"]
=>
[1 ,3 ,3 ]
map length ["aloo","d","e"]
=>
[4 ,1 ,1 ]
map length ["xnx","y","z","w"]
=>
[3 ,1 ,1 ,1 ]
以便
map (map length) [["aloo","d","e"],["xnx","y","z","w"]]
=>
[[4 ,1 ,1 ],[3 ,1 ,1 ,1 ]]
接着
map maximum [[4 ,1 ,1 ],[3 ,1 ,1 ,1 ]]
=>
[ 4 , 3 ]
因此,只需命名您的临时变量,然后随意使用它们。
推荐阅读
- sql - 将 MDDYYYY 或 MDYYYY 格式字符串插入日期列
- python - 我如何修补方法并返回 pytest 中的传入参数?
- regex - 括号之间的正则表达式匹配在括号内的第一个空格处停止
- c# - KeyHook 用于检测同时按下的多个键
- python - sympy 中是否存在离散有限随机变量的复合分布?
- java - 如何处理实现 Comparable和 Not Comparable的类
? - python-2.7 - 从最小数量的 Sentine-1 SAR 图像创建马赛克,该图像具有最大覆盖多边形 shapefile
- django - 每个 Wagtail 页面上的 Django 表单,例如 base.html 页脚中的联系表单
- android - android studio中的firebase数据更改方法
- javascript - 当我在 JavaScript 中向 Firebase 实时数据库添加新值时如何保存当前日期/时间