gpt4 book ai didi

python - 如何将规则添加到 python 中的列表中

转载 作者:行者123 更新时间:2023-12-01 06:02:26 25 4
gpt4 key购买 nike

我基本上需要能够限制可以附加到列表中的项目。就像在纸牌游戏中一样,如果要按字母顺序跟随该项目,我需要将一个项目添加到列表中,否则会返回错误。例如;字母d可以附加在字母c前面,如果字母不同或顺序错误则卡不会被移动。

下面的代码是迄今为止我能做的最好的代码。

a = ['a','c','e','j','h']

b = ['b','d','f','i','g']

def list_a():

loop = 0
choice = 0

while loop == 1:
print('''Choose from one of the following options:
1. Move item from list b to list a
2. add item to list a!''')

choice = int(input("What would you like to do?: "))
if choice == 1:
move_item()

elif choice == 2:
add_item()
return choice

print('List a: ',a)
print('List b: ',b)




def move_item():
loop = 0
choice = 0

while loop == 1:
print('''Choose from one of the following options:
1. Move item 1
2. move item 2
3. Move item 3
4. move item 4
5. Move item 5!''')

choice = int(input("What would you like to do?: "))
if choice == 1:
a.append(b.pop(0))

elif choice == 2:
a.append(b.pop(1))

elif choice == 3:
a.append(b.pop(2))

elif choice == 4:
a.append(b.pop(3))

elif choice == 5:
a.append(b.pop())

return choice

def add_item():
print()

list_a()

最佳答案

创建列表的子类并覆盖setitem、插入和/或存储业务逻辑所需的任何其他内容。

class MyList(list):
def passes_rules(self, idx, value):
""" Checks to see if this value can be set to this index """

def __setitem__(self, idx, value):
if self.passes_rules(idx, value):
super(MyList, self).__setitem__(idx, value)

其他人可能会告诉我们 setitem 是否足够,或者您是否还需要担心追加和插入。实验也可以,但请告诉我你的发现。 :)

关于python - 如何将规则添加到 python 中的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9625928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com