打开元组列表以检查每个元组中的中间值是否不超过一定数量 [英] Unpack list of tuples to check that middle value in each tuple doesn't exceed a certain amount

查看:50
本文介绍了打开元组列表以检查每个元组中的中间值是否不超过一定数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将每个元组解包到一个元组列表中,并检查每个元组的中间值未超过方程式中的某个特定值.我不断得到)期望,但=>找到了."我已经在尝试通过这种方式来推动我的知识,所以我不知道这是怎么回事?

  def多少(m:Int,n:Int):List [Any] = {val a =((m-1)至(n-1)).toListval b = a.map(i =>if((((7/9.0 * i + 1/9.0)%1)== 0)(7 * i + 2,i,(7/9.0 * i + 1/9.0).toInt)else n + 1)val c = b.map((i._1,i._2,i._3)=>如果(9 *(i._3)+1< = n)(i._1,i._2,i._3)否则n + 1)C} 

解决方案

if / else 的第一条规则是双方的类型应匹配.

让我们看一下第一个(经过重新格式化以使其更易于阅读).

  a.map(i =>如果((((7/9.0 * i + 1/9.0)%1)== 0)(7 * i + 2,i,(7/9.0 * i + 1/9.0).toInt)//(Int,Int,Int)元组else n + 1//整数) 

因此,如果 a 类似于 List(5,6,7),则结果将为 List(8,(37,5,4),8).这是类型为 List [Any] 的列表.这是一个非常糟糕的信号.每当您在Scala代码中遇到键入 Any 时,它都会引发一个红色标记.

接下来,您尝试在此列表上进行 map().不仅语法错误,每个元素的类型均为 Any .您不能将每个元素都视为一个元组,因为它不是一个 Tuple ,而是一个 Any .您不能将 1 添加到元素,因为它不是 Int ,它是 Any .

该从头开始回想一下.

I've been trying unpack each tuple in a list of tuples and check to see that the middle value in each tuple doesn't exceed a certain amount in an equation. I keep getting ") expected but => found." I'm already pushing my knowledge by attempting this, so I have no idea what is wrong?

def howmuch(m: Int, n: Int): List[Any] = {
  val a = ((m-1) to (n-1)).toList
  val b = a.map(i =>
    if (((7 / 9.0 * i + 1 / 9.0) % 1) == 0) (7*i+2,i,(7 / 9.0 * i + 1 / 9.0).toInt) else n+1)

  val c = b.map((i._1,i._2,i._3) => if (9*(i._3)+1 <=n) (i._1,i._2,i._3) else n+1)
  c
}

解决方案

The first rule of if/else is that the types of both sides should match.

Let's look at the first one (reformatted to make it easier to read).

a.map(i =>
    if (((7 / 9.0 * i + 1 / 9.0) % 1) == 0)
      (7*i+2, i, (7 / 9.0 * i + 1 / 9.0).toInt) //(Int,Int,Int) tuple
    else n+1                                    //Int
  )

So if a is something like List(5,6,7) then the result will be List(8, (37,5,4), 8). This a list of type List[Any]. That's a very bad sign. Whenever you encounter type Any in Scala code it should raise a red flag.

Next you're trying to map() over this list. Not only do you get the syntax all wrong, each element is type Any. You can't treat each element as if it were a tuple because it's not a Tuple, it's an Any. You can't add 1 to an element because it's not an Int, it's an Any.

Time to go back and rethink this from the beginning.

这篇关于打开元组列表以检查每个元组中的中间值是否不超过一定数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆