将同一项多次追加到列表中

2024-06-16 10:15:28 发布

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

我正在做一个程序,将选择一个赢家的多个用户和显示赢家。我已经计算了百分数,即用户名将被追加到列表的次数。在

澄清:

  1. 计算百分比
  2. 将用户用户名追加到列表中的次数与百分数相同。在
  3. 从列表中随机选择一个人。在
  4. 显示获胜者。在

到目前为止我的代码是:

probabilities = []

    print("Calculating", player1 + "'s luck!")
    time.sleep(3)
    player1num = random.randint(0,100)
    newnum = player1num / 2
    newnumadded = newnum + 10
    if newnumadded > 50:
        bonusnum = newnumadded + 25
        print(player1 + " Your number is:", str(player1num) + "! You have a percentage to win of: ", str(bonusnum) + "%!")
    else:
        print(player1 + " Your number is:", str(player1num) + "! You have a percentage to win of: ", str(newnumadded) + "%!")

我试图使player1变量(即用户名)存储在概率列表中的次数与百分数相同。在

约翰有百分之七十九的胜算。把约翰列入名单79次


Tags: 用户number列表youris次数用户名print
2条回答

只需在列表中添加x个元素x次:

import random

probabilities = []
player1="John"

print("Calculating", player1 + "'s luck!")

player1num = random.randint(0,100)
newnum = player1num / 2
newnumadded = newnum + 10
if newnumadded > 50:
    bonusnum = newnumadded + 25
    print(player1 + " Your number is:", str(player1num) + "! You have a percentage to win of: ", str(bonusnum) + "%!")
    probabilities.extend([player1 for x in range(0,int(bonusnum))])

else:
    print(player1 + " Your number is:", str(player1num) + "! You have a percentage to win of: ", str(newnumadded) + "%!")
    probabilities.extend([player1 for x in range(0,int(newnumadded))])

print(probabilities)

如果要将player1添加到列表percentage_listpercentage_number次,可以执行以下操作:

percentage_list.extend([player1] * percentage_number)

相关问题 更多 >