在 Django/Python 中将 string 转换为 int 时遇到问题

发布于 2024-12-04 17:50:20 字数 3277 浏览 0 评论 0原文

我正在尝试将字符串转换为 int,以便我可以保留运行总计,并希望能够在 django 模板中输出。

def stats(request):
    stats = []
    players = Player.objects.all()

    for player in players:
        player_stats = PlayerStat.objects.filter(player__id=player.pk)
        for n,stat in enumerate(player_stats):
            if n == 0: 
                    passing_completions = stat.passing_completions
            else:
                passing_completions += stat.passing_completions

        stats.append((player.first_name, player.last_name, player.team, passing_completions))

    return render_to_response('preps/stats.html', {'stats': stats, })

我尝试在 stat.passing_completions 周围添加 int() ,但随后只会抛出错误 invalid Literal for int() with base 10: ''

然后我使用 isdigit() 方法来确保只有带有数字的字符串才尝试像这样转换:

for player in players:
    player_stats = PlayerStat.objects.filter(player__id=player.pk)

    for n,stat in enumerate(player_stats):
        if n == 0: 
            if stat.passing_completions.isdigit():
                passing_completions = int(stat.passing_completions)
        else:
            if stat.passing_completions.isdigit():
                passing_completions += int(stat.passing_completions)

    stats.append((player.first_name, player.last_name, player.team, passing_completions))

但随后我在渲染时收到 Caught TypeError 错误:'int' object不是可迭代的

模型结构

class PlayerStat(models.Model):
    player = models.ForeignKey(Player)

    week_num = models.CharField(
        max_length = 10,
        choices = (('1', 'Sep 2nd',), ('2', 'Sep 9th',), ('3', 'Sep 16th',),('4', 'Sep 23rd',), ('5', 'Sep 30th',), ('6', 'Nov 2nd',),('7', 'Nov 7th',), ('8', 'Nov 14th',), ('9', 'Nov 21st',),('10', 'Nov 28th',), ('11', 'Dec 4th',), ('12', 'Dec 11th',), ),
        blank = True,
        null=True
        )
    rushing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Attempts",
        blank=True
        )
    rushing_yards = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Yards",
        blank=True
        )
    rushing_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Touchdowns",
        blank=True
        )
    passing_completions = models.CharField(
        max_length = 100,
        verbose_name = "Passing Completions",
        blank=True
        )
    passing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Passing Attempts",
        blank=True
        )
    passing_yards = models.CharField(
        max_length = 100,
        verbose_name = "Passing Yards",
        blank=True
        )
    passing_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Passing Touchdowns",
        blank=True
        )
    receptions = models.CharField(
        max_length = 100,
        verbose_name = "Receptions",
        blank=True
        )
    receiving_yards = models.CharField(
        max_length = 100,
        verbose_name = "Receiving Yards",
        blank=True
        )
    receiving_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Receiving Touchdowns",
        blank=True
        )

任何帮助将不胜感激。

谢谢

I'm trying to convert a string into an int so that I can keep a running total and would like to be able to output in the django template.

def stats(request):
    stats = []
    players = Player.objects.all()

    for player in players:
        player_stats = PlayerStat.objects.filter(player__id=player.pk)
        for n,stat in enumerate(player_stats):
            if n == 0: 
                    passing_completions = stat.passing_completions
            else:
                passing_completions += stat.passing_completions

        stats.append((player.first_name, player.last_name, player.team, passing_completions))

    return render_to_response('preps/stats.html', {'stats': stats, })

I've tried adding int() around stat.passing_completions but then that just throws the error invalid literal for int() with base 10: ''.

So then I used the isdigit() method to make sure only strings with digits were trying to be converted like this:

for player in players:
    player_stats = PlayerStat.objects.filter(player__id=player.pk)

    for n,stat in enumerate(player_stats):
        if n == 0: 
            if stat.passing_completions.isdigit():
                passing_completions = int(stat.passing_completions)
        else:
            if stat.passing_completions.isdigit():
                passing_completions += int(stat.passing_completions)

    stats.append((player.first_name, player.last_name, player.team, passing_completions))

but then I get the error of Caught TypeError while rendering: 'int' object is not iterable

model Structure

class PlayerStat(models.Model):
    player = models.ForeignKey(Player)

    week_num = models.CharField(
        max_length = 10,
        choices = (('1', 'Sep 2nd',), ('2', 'Sep 9th',), ('3', 'Sep 16th',),('4', 'Sep 23rd',), ('5', 'Sep 30th',), ('6', 'Nov 2nd',),('7', 'Nov 7th',), ('8', 'Nov 14th',), ('9', 'Nov 21st',),('10', 'Nov 28th',), ('11', 'Dec 4th',), ('12', 'Dec 11th',), ),
        blank = True,
        null=True
        )
    rushing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Attempts",
        blank=True
        )
    rushing_yards = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Yards",
        blank=True
        )
    rushing_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Touchdowns",
        blank=True
        )
    passing_completions = models.CharField(
        max_length = 100,
        verbose_name = "Passing Completions",
        blank=True
        )
    passing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Passing Attempts",
        blank=True
        )
    passing_yards = models.CharField(
        max_length = 100,
        verbose_name = "Passing Yards",
        blank=True
        )
    passing_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Passing Touchdowns",
        blank=True
        )
    receptions = models.CharField(
        max_length = 100,
        verbose_name = "Receptions",
        blank=True
        )
    receiving_yards = models.CharField(
        max_length = 100,
        verbose_name = "Receiving Yards",
        blank=True
        )
    receiving_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Receiving Touchdowns",
        blank=True
        )

Any help would be appreciated.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冷血 2024-12-11 17:50:20

我有时会使用这个愚蠢的技巧:

 a = int('0' + someString)

在字符串前面添加一个零可以保证字符串中至少有“0”。
现在,可以肯定的是,您可以使用正则表达式从“'0'+someString”中提取所有数字。

I sometimes use this stupid trick :

 a = int('0' + someString)

Adding a zero in front of a string guaranties me to have at least "0" in the string.
Now, to be sure, you may extract all the digits from the "'0'+someString" with a regular expression.

心头的小情儿 2024-12-11 17:50:20

我知道这是一个老问题,但如果有人需要,这里有一个我用来毫无问题地将字符串转换为 int 的小解决方案:

def int_or_0(value):
    try:
        return int(value)
    except:
        return 0

就是这样。 ;)

I know this is an old question, but if someone needs, here is a small solution I use to convert strings to int without problems:

def int_or_0(value):
    try:
        return int(value)
    except:
        return 0

Just it. ;)

你另情深 2024-12-11 17:50:20

您应该检查 stat.passing_completions 是否不是空字符串。你可以使用:

for player in players:
    player_stats = PlayerStat.objects.filter(player__id=player.pk)
    for n,stat in enumerate(player_stats):
        if n == 0 and stat.passing_completions:  # n is 0 and passing_completions is something meaningful
                passing_completions = int(stat.passing_completions)
        elif stat_passing_completions:  # n is not 0
            passing_completions += int(stat.passing_completions)
        else:
            pass  # in this case, stat.passing_completions is an empty string ('')

    stats.append((player.first_name, player.last_name, player.team, passing_completions))

You should check if stat.passing_completions is not an empty string. You could use:

for player in players:
    player_stats = PlayerStat.objects.filter(player__id=player.pk)
    for n,stat in enumerate(player_stats):
        if n == 0 and stat.passing_completions:  # n is 0 and passing_completions is something meaningful
                passing_completions = int(stat.passing_completions)
        elif stat_passing_completions:  # n is not 0
            passing_completions += int(stat.passing_completions)
        else:
            pass  # in this case, stat.passing_completions is an empty string ('')

    stats.append((player.first_name, player.last_name, player.team, passing_completions))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文