我有一个清单:
a=['I', 'O', 'O', 'I', 'I', 'O', 'O', 'I', 'I', 'U', 'U', 'I', 'I', 'S', 'S', 'I', 'X', 'X', 'X', 'X']
我想处理列表以便
if a[0]=='I':
它会移除下一个'I'
if a[0]=='O'
它会移除下一个3 'O'
的if a[0]=='U'
它会移除下一个'U'
S
和X
不做任何事情然后a[1]
...直到结束
a的结果将是
a=['I','O','I','I','U','I','S','S','X','X','X','X']
它不一定需要是我可以创建另一个列表的相同列表。
答案 0 :(得分:2)
首先你要循环直到[0]是' X'或者' S'
while a[0] not in "XS": # this will break if a is ever totally empty ...
if a[0] == "I":
a = takeNext(a,"I")
elif a[0] == "O":
a = takeNext(a,"O",3)
elif a[0] == "U":
a = takeNext(a,"U")
然后你所要做的就是编写一个类似于
的takeNext方法def takeNext(a_list,whatToTake,howManyToTake=1):
#write this function
#keep in mind you will also have to define some edge cases
#what happens if the list doesnt have what you should remove
#or only has 2 when you are supposed to take 3
请记住,这有点过于简化,根据您的问题陈述,有几个边缘情况没有定义的行为,所以您必须做一些工作来定义边缘情况及其行为(I确实包括一些边缘情况的例子,但我没有声称这是所有边缘情况)