【问题标题】:"sample larger than population or is negative" but list contains more elements than sample size in list retrieved from url?“样本大于总体或为负数”但列表包含的元素多于从 url 检索的列表中的样本大小?
【发布时间】:2022-01-10 06:17:56
【问题描述】:

python 3:我正在尝试编写一个宾果游戏,它询问用户 1-3 个玩家,为每个玩家分配一个名字,然后通过从 listOfStrings 列表中选择 25 个元素来创建他们的 Bingo 卡。该列表包含 53 个元素,它们都是字符串。我收到错误“ValueError:样本大于总体或为负”但 25

import urllib.request
import random
listOfStrings = []

def createList():
    try:
       with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
           d = f.read().decode('utf-8')
           split= d.split("\n")
           listOfStrings = split
    except urllib.error.URLError as e:
        print(e.reason)


def players(listOfStrings):
    noPlayers = input("How many players would like to play Bingo? Choose 1-3: ")
    if noPlayers == "1":
        name = input("What is the name of player 1? ")
        player1card = random.sample(list(listOfStrings), 25) 


createList()
players(listOfStrings)
print(player1card)

【问题讨论】:

  • 如果出现问题,请告诉我如何使问题变得更好
  • 您应该在createList() 中将listOfString 设为全局或从函数中返回它。更好的是,根本不要全局初始化它 - 你会看到 actual 错误消息。

标签: python-3.x list random population


【解决方案1】:

createList() 函数永远不会返回listOfStrings,所以当你将它传递给players() 时它仍然是空的。

要修复它,您需要:

def createList():
   # your function
   return listOfStrings 

def players(listOfStrings):
    player1card = []
    # your function
    return player1card 
    
listOfStrings = createList()
player1card = players(listOfStrings)
print(player1card)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2015-06-27
    • 1970-01-01
    • 2017-01-14
    • 2014-01-18
    相关资源
    最近更新 更多