我用几个简单的方法创建了一个列表类。列表类保留新列表的旧值Python
class ListQ(object):
"""List object creation"""
def __init__(self, earlier_list=[]):
self.list=earlier_list
def isEmpty(self):
"""checks if list is empty"""
if len(self.list)==0:
return(True)
else:
return(False)
def put(self, new_item):
"""puts new_item last in list"""
self.list.append(new_item)
def get(self):
"""returns the next item in line"""
self.first_item = self.list.pop(0)
return self.first_item
我也有一个函数来帮助创建这些列表。 (帮助解决BTW魔法卡招)
def create_card_list(card_list=None):
"""creates listQ of cards from user input"""
if card_list!=None: #if user already has list of cards
for item in card_list:
item=replace_card_strings(item) #replaces any strings in list
if item == False:
print('One of your cards does not exist, list creation failed')
return(False)
cards=ListQ(card_list)
()函数已经得到很好的测试,我不相信这是有过错的,但在这里它是无论如何的replace_card_strings。
def replace_card_strings(word):
"""replaces strings of words with their numbers and returns edited list"""
if type(word)!=int:
if word.lower()=='one':
word=1
elif word.lower()=='two':
word=2
elif word.lower()=='three':
word=3
elif word.lower()=='four':
word=4
elif word.lower()=='five':
word=5
elif word.lower()=='six':
word=6
elif word.lower()=='seven':
word=7
elif word.lower()=='eight':
word=8
elif word.lower()=='nine':
word=9
elif word.lower()=='ten':
word=10
elif word.lower()=='jack':
word=11
elif word.lower()=='queen':
word=12
elif word.lower()=='king':
word=13
elif word.lower()=='ace':
word=1
else:
word=False #if card doesnt exist
return(word)
当我运行下面的测试的时候是问题出现的时候。
cards=create_card_list(['one', 2, 3])
one=cards.get()
two=cards.get()
three=cards.get()
print(one, two, three)
if one==1 and two==2 and three==3:
print("create_card_list gives the correct answer")
else:
print("create_card_list gives the wrong answer")
它打印出该功能已给出错误的答案和 的print(one, two, three)
打印one 2 3
这是最初的名单。
任何人有一个想法,我已经搞砸了?
您不应该首先创建列表类,因为那里已经有Python列表。 – 2015-02-08 09:12:30
是的,我知道,但分配是创建这个类,所以我没有选择。 – rickri 2015-02-08 09:13:38
此外,您*需要*复制ListQ构造函数中的列表! – 2015-02-08 09:14:05