简体   繁体   English

如何从元组列表中获取元素列表?

[英]How to get a list of elements from a list of tuples?

How to get an element inside of a list of tuples?如何获取元组列表中的元素? For example例如

list = [(Tris, 23, 1.40), (Aif, 20 , 1.70)] 

I want all the ages我想要所有年龄

[23,20]

I know that I can use我知道我可以使用

age = (_,x,_) = x 

But it only works with tuples and not a tuple inside a list.但它只适用于元组,而不适用于列表中的元组。

You will need to perform a map ping where for each item in the list you map it to its age.您需要对列表中的每个项目执行map ping,将其映射到其年龄。

You can do this with the map :: (a -> b) -> [a] -> [b] function , so this will look like:你可以用map :: (a -> b) -> [a] -> [b] function 来做到这一点,所以这看起来像:

allAges = map …

where I leave filling in as an exercise.我留下填写作为练习。

you can solve it recursively like:你可以递归地解决它,如:

allages [] = []
allages ((_,x,_):xs) = x : allages xs

I know that I can use我知道我可以使用

age (_,x,_) = x

But it only works with tuples and not a tuple inside a list.但它只适用于元组,而不适用于列表中的元组。

Why are you saying this?你为什么这么说? Surely if you know that当然如果你知道

age   (_,x,_)  =  x

then you also know that那么你也知道

ages [(_,x,_)] = [x]

and

ages [(_,x,_), (_,y,_)]          = [x,y]
ages [(_,x,_), (_,y,_), (_,z,_)] = [x,y,z]
....

etc. And since we've already established that等等 因为我们已经确定了

ages [         (_,y,_), (_,z,_)] = [  y,z]
ages [                  (_,z,_)] = [    z]

so that surely所以肯定

ages [                         ] = [     ]

we can just write down these equations,我们可以写下这些方程,

ages [                       ] = [                               ]
ages ([(_,x,_)] ++ moreTuples) = ages [(_,x,_)] ++ ages moreTuples

and since we know that ages [(_,x,_)] = [x] , it's并且因为我们知道ages [(_,x,_)] = [x] ,它是

ages [                       ] = [                               ]
ages ([(_,x,_)] ++ moreTuples) = [        x   ] ++ ages moreTuples

so now all that's left to make it valid Haskell syntax is to rewrite the first equation's argument using the : operator, along the lines of所以现在要让它成为有效的 Haskell 语法,剩下的就是使用:运算符重写第一个方程的参数,沿着

      [   a   ] ++ moreTuples ==
          a     :  moreTuples

and you're done.你就完成了。

So in the end you did know how to do this.所以最后你确实知道如何做到这一点。

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

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