首页 > 解决方案 > Python:typeerror:'list'对象不可调用

问题描述

我是一个学习python的初学者。我正在尝试制作一个程序,它可以在不使用 random.shuffle 或 random.choice 的情况下洗牌。当我使用我的程序时,我可以将我的列表洗牌并打印出来,然后我可以打印出原始的一副牌。但是,当我再次洗牌时,会发生错误。

发生的错误

任何人都可以帮忙吗?

from random import randint
#deckbuild function creates the deck of 52 cards from a normal deck
def deckbuild():
  #program will create a deck of cards when the program is launched
  cards = []
  signs = ["Hearts", "Diamonds", "Clubs", "Spades"]
  cardletters = ["J", "Q", "K", "A"]
  deck = []
  #Adding content to the deck
  for i in range(2,11):
    cards.append(str(i))
    #this will generate the numbers 2 to 10 hat will be used for the cards
  for r in range(4):
    cards.append(cardletters[r])
    #adding card letters to cards
  for final in range(4):
    for k in range(13):
      fincard = (cards[k] + " of " + signs[final])
      deck.append(fincard)
      #adds the final product of cards into a list that will be used to put into functions
  for numofcard in range(52):
    return deck

#List of functions that will be used
#shuffle function takes in a list and randomly shuffles it
def shuffle(listinput):
  list_range = range(0, len(listinput))
  for i in list_range:
    j = randint(list_range[0], list_range[-1])
    listinput[i], listinput[j] = listinput[j], listinput[i]
  return listinput

def printdeck(x):
  print('Here is your deck of cards ')
  #prints the deck in a vertical list
  for num in range(52):
    print(x[num])


print('Hello, welcome to the card shuffler program')
print('''This program allows you to shuffle a full deck of cards in a digital world''')
loop = True
while(loop == True):
  loop = False
  carddeck = deckbuild()
  print('Here is a list of things you can do')
  print('1. Shuffle and view shuffled deck')
  print('2. View Orginal deck')
  print('3. Quit')

  userinput = input('''Type in the number that corresponds with the feature you would like to choose ''')

  if userinput == "1":
    shuffle = shuffle(carddeck)
    print('''Shuffled your list
    ''')
    printdeck(shuffle) 
    loop = True 
  elif userinput == "2":
    printdeck(carddeck)
    loop = True
  elif userinput == "3":
    print('Thanks for playing')
    quit()
  else: 
    print('That wasnt an item from the list')
    loop = True

标签: python

解决方案


问题在于,shuffle函数的名称。在第一次迭代中,当您调用 shuffle 时,它​​会分配由shuffle()函数返回的值 a list。现在 shuffle 是 a 的实例list而不是函数。因此,当您再次调用 shuffle 时,shuffle它​​不再是一个函数而是一个列表,因此您会得到一个错误list is not a callable

为了解决这个问题,我们只需要更改使用shuffle与函数相同的单词的变量的名称。它可以是任何东西,但请确保它们不会重复...

在您的 while 循环中更改为:

if userinput == "1":
  shuffled = shuffle(carddeck)
  print('''Shuffled your list''')
  printdeck(shuffled)

推荐阅读