【问题标题】:convert js function to Python [closed]将js函数转换为Python [关闭]
【发布时间】:2020-08-06 14:46:49
【问题描述】:

我正在研究将罗盘度数转换为表示方向的字符串。还有另一个 SO 帖子可以做到这一点here

这是一个稍微修改以将完整方向表示为单词的答案,而只是缩写,有人知道如何将其转换为 Python 函数吗?我希望返回一个代表 8 个基本方向的字符串...由Edward Brey Feb 13 '19 at 18:29 回答

function getCardinalDirection(angle) {
    const directions = ['↑ North', '↗ North East', '→ East', '↘ South East', '↓ South', '↙ South West', '← West', '↖ North West'];
    return directions[Math.round(angle / 45) % 8];
}

【问题讨论】:

  • 您的尝试在哪里,有什么问题?这个函数没什么复杂的,用 Python 再写一遍应该很简单

标签: javascript python


【解决方案1】:

这比你想象的要简单:

def getCardinalDirection(angle):
    directions = ['↑ North', '↗ North East', '→ East', '↘ South East', '↓ South', '↙ South West', '← West', '↖ North West']
    return directions[round(angle / 45) % 8]  # round() is a built-in function

示例输出:

>>> getCardinalDirection(50)
'↗ North East'
>>> getCardinalDirection(220)
'↙ South West'
>>> getCardinalDirection(-37)
'↖ North West'
>>> getCardinalDirection(188)
'↓ South'

【讨论】:

    【解决方案2】:

    就这么简单:

    def get_card_direction(angle):
        directions = ['↑ North', '↗ North East', '→ East', '↘ South East', '↓ South', '↙ South West', '← West', '↖ North West']
        return directions[round(angle/45) % 8]
    print(get_card_direction(50)) # output ↗ North East
    

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2017-04-18
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多