【问题标题】:How can do a tuple comparison in coffeescript similar to that in python?如何在coffeescript中进行类似于python中的元组比较?
【发布时间】:2024-01-19 09:49:01
【问题描述】:

这是我的功能

st3 = (x, y) ->
  console.log "#{x?}, #{y?}"
  if [x?, y?] is [true, true]   # <- this is the line
    'good'
  'bad'

这是输出

true, true
bad

我希望能够像在 python 中那样进行元组比较。

在python中,if可以大致写成

 if (x, y) == (True, False):
   return 'good'

coffescript if 循环被翻译成这样的javascript

if ([x != null, y != null] === [true, true]) {
  'good';
}

这就是为什么 this 不会被评估为 true。

在coffeescript中有没有其他的表达方式?

【问题讨论】:

  • 你不能用if x is true and y is true吗?
  • 在这种情况下是肯定的。但是如果元组大小增加了怎么办?我正在寻找更优雅的解决方案。
  • 这里没有什么不优雅的,如果你有任意大小的参数,你可以循环参数并评估条件。或者,您可以编写自己的元组原型并从那里扩展。

标签: coffeescript


【解决方案1】:

如果您想检查您的所有参数是否不是None,那么我会这样做:

def check_all(*args):
    return all(arg is not None for arg in args)

如果你想检查它们是否都是True(就像字面意思一样),那么你可以使用

def check_all(*args):
    return all(arg is True for arg in args)

如果您想获取一个列表(而不是可变数量的参数,请删除星号。

【讨论】:

    最近更新 更多