python - 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
解决方案
问题在于,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)
推荐阅读
- android - Xamarin Forms 允许在播放视频时从 Android 上的另一个应用程序播放音乐
- database - 迁移 wordpress 网站并使用插件更改 URL 后链接不起作用
- python - 在 Python 中,我无法使用 PIL 正确打开一些 png 图像
- docker - Docker Windows 容器无法解析 host.docker.internal
- facebook - 2021 年如何在 Facebook 上获得 URL 赞
- c# - JSON.NET 通过填充来覆盖字典的值
- python - 打印列表中的每个项目及其索引,先打印索引然后打印项目
- c# - C# 如何更改程序中的分组?(初学者)
- reactjs - 如何在 Cloud Firestore 中的数组内增加地图中的值?
- c# - 从 DB 读取的变量名称而不是地址(偏移量)