【问题标题】:Interpreting double digit numbers解释两位数
【发布时间】:2013-06-30 15:06:09
【问题描述】:

所以,这段代码有点麻烦。

if s.get("home") < s.get("away"):
        scoringplays = scoringplays + s.get("away") + "-" + s.get("home") + " " + game.get("away_team_name")
    elif s.get("home") > s.get("away"):
        scoringplays = scoringplays + s.get("home") + "-" + s.get("away") + " " + game.get("home_team_name")
    else:
        scoringplays = scoringplays + s.get("home") + "-" + s.get("away") + " Tied"

它从 MLB 中提取棒球比赛的比分并将其发布到 reddit,如下所示:

4-3 获胜队名

但是,我注意到如果其中一个分数是两位数,代码似乎只读取第一个数字,因此 10-2 的分数会显示如下:

2-10 失去队名

我搜索了一下,也许我使用了错误的搜索词,但我似乎无法在这里找到答案。任何帮助将不胜感激。

【问题讨论】:

  • 对不起。是蟒蛇。谢谢你这么亲切。

标签: python digits


【解决方案1】:

看起来你在比较字符串:

>>> "10" < "2"
True

比较它们的整数版本:

if int(s.get("home")) < int(s.get("away"))

如果字典中缺少键,则dict.get 默认返回None。你也可以传递你自己的默认值。

home_score = int(s.get("home", 0))  # or choose some other default value
away_score = int(s.get("away", 0))

if home_score < away_score:
     #do something

演示:

>>> int("10") < int("2")
False

【讨论】:

  • 我在尝试时收到以下错误:TypeError: int() argument must be a string or a number, not 'NoneType'
  • @user2536657 这意味着s.get("home")s.get("away") 正在返回None。您也可以使用默认值:s.get("home", 0),如果没有找到键“home”,这里将返回 0。
猜你喜欢
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
相关资源
最近更新 更多