如何从带有数字的字符串中去掉字母,以便可以将其更改为int并进行排序

2024-07-07 09:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个掷骰子游戏,其中的分数和球员必须存储在一个数组,然后打印出来,作为记分牌的顺序。我可以做所有这些,但排序记分牌。你知道吗

我已经计算出我需要从字符串中去掉字母(player1 37到just 37)。我目前使用的代码是delchars = Player1.join(c for c in map(chr, range(256)) if not c.isalnum()),但它似乎不起作用,任何人都知道该怎么做。你知道吗

#code for entering Player1 
let= True
while let == True:
    delay_print("player 1 enter your username\n")
    Player1 = input()
    if len(Player1) > 20 or len(Player1) < 3:
        print("That is too long or too short, please try again") 
    else:
        let = False
#code for entering Player2
tel = True
while tel == True:
    delay_print("player 2 enter your username\n")
    Player2 = input()
    if len(Player2) > 20  or len(Player2) < 3:
        print("That is too long, or too short, please try again")
    else:
        tel = False

我期望的结果是能够打印出一个记分板,顺序。 此记分牌的当前代码为

print("first place is ", scoreboard[0] ,
      "\nsecond place is ", scoreboard[1], 
      "\nthird place is "  ,scoreboard[2], 
      "\nfourth place is " ,scoreboard[3], 
      "\nfifth place is "  ,scoreboard[4])

Tags: ortrueforlenifisplacetoo
3条回答

而不是

delchars = Player1.join(c for c in map(chr, range(256)) if not c.isalnum())

使用

delchars = "".join([c for c in Player1 if not c.isalnum()])

一种为列表创建排序记分板的方法。我不明白为什么你应该连接你的球员名字和分数,虽然,这些应该是独立的变量。你知道吗

n=0
scoreboard = ["player1 37","player3 45","player2 75", "player32 43"]
def myFunc(e):
    return int(e.split(" ")[1])
scoreboard = sorted(scoreboard, key=myFunc, reverse=True)
print("SCOREBOARD:")
for players in scoreboard:
    print("{0}: {1}".format(n+1,scoreboard[n]))
    n+=1

正如其他人提到的,你可能正试图用一种非常奇怪的方式来做这件事。回答您的问题:

myString = "player1 37"
score = int(myString.split(" ").pop())

这里发生了什么:它将字符串拆分为一个列表,在空格处进行划分。Pop获取list的最后一个元素,int()将其转换为整数,因为首先将分数作为字符串是一个非常糟糕的主意。你知道吗

相关问题 更多 >