作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我基本上需要能够限制可以附加到列表中的项目。就像在纸牌游戏中一样,如果要按字母顺序跟随该项目,我需要将一个项目添加到列表中,否则会返回错误。例如;字母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/
我是一名优秀的程序员,十分优秀!