【问题标题】:Making a list of randomly selected items列出随机选择的项目
【发布时间】:2021-04-24 14:11:08
【问题描述】:

我需要制作一个包含一系列 10 个数字和五个字母的列表或元组。从列表中随机选择四个数字或字母,并打印一条消息,说明任何匹配这四个数字或字母的彩票中奖。

代码我试过了,但不知道要写什么:

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e']

winner = []

print("winning ticket is...")

while len(winner) > 4:
    pulled_item = choice(possibilities)

    if pulled_item not in winner:
        print(f"we pulled a {pulled_item}!")
        winner.append(pulled_item)

请提供代码 这会告诉您选择的号码和中奖号码。

【问题讨论】:

  • 首先你需要搜索在python中你能做些什么“随机”选择。
  • 这太模糊了。什么在起作用?什么不是?您需要帮助查找如何从列表中选择随机项目吗?
  • 如果您进行了测试while len(winner) < 4,这可能会更好。您的测试始终是False。所以什么都不会发生。

标签: python class


【解决方案1】:

如果你可以使用随机包那么

from random import randint

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e']
winning_ticket = ""
print("Winning ticket is...")

for x in range(4):
    winning_ticket += str(possibilities[randint(0, len(possibilities)-1)])
    
print(f"Any ticket matching {winning_ticket} wins a prize!")

【讨论】:

  • 我也想选择这四个数字
  • 哪四个数字?被选中是什么意思?
【解决方案2】:

您可以使用 Python 内置随机库中的选择功能。

from random import choice

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e']

# choose four items from the possibilities
chosen = [str(choice(possibilities)) for _ in range(4)]

# print the four chosen items
print(f"Any ticket matching {''.join(chosen)} wins a prize!")

此代码将四个拉出的数字或字母组成一个数组,然后在最后打印整个数组。

【讨论】:

    【解决方案3】:
    from random import choice
    lottery = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd');
    
    win = [];
    
    for value in range(4):
        choose = choice(lottery);
        win.append(choose);
    
    print(f"Any ticket matching {win} wins a prize")
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 请记住,Stack Overflow 不仅仅是为了解决眼前的问题,而是为了帮助未来的读者找到类似问题的解决方案,这需要了解底层代码。这对于我们社区的初学者和不熟悉语法的成员来说尤其重要。鉴于此,您能否edit 您的回答包括对您正在做什么的解释以及为什么您认为这是最好的方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多