首页 > 解决方案 > 将计数器值更改为字符串

问题描述

这个项目一小时后到期,我已经尝试了我知道的每一种方法,但我就是无法让这一部分工作。真的需要帮助。我想将计数器值更改为已将结果相加的结果,因此我不想打印每个计数器的总数,而是想打印一个字符串

# Compare countA to distance:
def raceAlgorithm(jack, slow, thunder) :
    # Race start point
    countA = 0

    # Length of the race
    distance = 20

    # message afer race is done
    msg = '\nRace Finished\nGetting results.'

    while countA != distance :
        dice = randint( 1, 6 )
        sleep( 1 )
        countA += 1

        if dice <= 2 :
            jack += 1
            # print(a)
        elif dice <= 4 :
            slow += 1
            # print(b)
        else :
            thunder += 1
            # print(c)
        if jack + slow + thunder == distance :
            print( msg )
            Position.append(jack)
            Position.append( slow )
            Position.append( thunder )
            Position.sort( reverse=True )

            # the horses totals
            print( *Position, sep='\n' )

            if Position[0] == jack:
                print( '\nThe winner is: ' + a )
            elif Position[0] == slow :
                print( '\nThe winner is: ' + b )
            elif Position[0] == thunder :
                print( '\nThe winner is: ' + c )
            else :
                print( )

例如,如果 jack 得到 10,slow 得到 5,而不是 print 10 和 5,我希望结果是马的名字。问题是由于每匹马的结果每次都是随机的,我无法更改特定的整数。我需要在它被添加到列表之前更改它。因此,如果千斤顶在此列表中的位置到达其打印千斤顶。

标签: pythonpython-3.x

解决方案


将列表更改为Position包含名称和值的列表,然后您可以按值排序并打印两者。

from operator import itemgetter

Position = [('jack', jack), ('slow', slow), ('thunder', thunder)]
Position.sort(key=itemgetter(1), reverse=True)
print(*Position)
print('\nThe winner is:', Position[0][0])

推荐阅读