在Python中执行三重剪切
我需要做三重切割。我的函数取int的参数列表,在该列表的某个地方有27和28。我需要做的是检查27或28之前的内容,27或28之前的内容根据首先出现的内容排在列表的底部,27或28之后的内容根据第二个内容排在列表的顶部 以下是一个例子:在Python中执行三重剪切,python,Python,我需要做三重切割。我的函数取int的参数列表,在该列表的某个地方有27和28。我需要做的是检查27或28之前的内容,27或28之前的内容根据首先出现的内容排在列表的底部,27或28之后的内容根据第二个内容排在列表的顶部 以下是一个例子: >>> test_list = [1, 28, 3, 4, 27, 5, 6, 7, 8] >>> triple_cut(test_list) >>> test_list = [5, 6, 7, 8, 28,
>>> test_list = [1, 28, 3, 4, 27, 5, 6, 7, 8]
>>> triple_cut(test_list)
>>> test_list = [5, 6, 7, 8, 28, 3, 4, 27, 1]
这是我到目前为止所拥有的
#find the index positions of the two jokers
find_joker1 = deck.index(27)
find_joker2 = deck.index(28)
print(find_joker1, find_joker2)
new_list = []
# use selection to check which joker occurs first
if(find_joker1 > find_joker2): # joker2(28) occurs first in the list
# loop throgh each element in the list that occurs before Joker1
# and move them to the end of the list
# move element that occur after Joker1(27) to the top of the list
for i in deck:
if(deck.index(i) > find_joker1): # elements that occur after second joker
new_list.append(i) # move those element to the top of the list
new_list.append(28) # add Joker2
for i in deck: # element between the two Jokers
if(deck.index(i) > find_joker2 and deck.index(i) < find_joker1):
new_list.append(i)
new_list.append(27)
for i in deck: # elements before the first joker
if(deck.index(i) < find_joker2):
new_list.append(i)
print(new_list)
可以通过切片来解决
def triple_cut(lst):
a=lst.index(27)
b=lst.index(28)
if a>b:
return lst[a+1:]+ lst[b:a+1]+ lst[:b]
else:
return lst[b+1:]+ lst[a:b+1]+ lst[:a]
实际发生的情况:
在较大的索引后切片所有内容。
从下索引到上索引的切片。
在索引较低的之前切片所有内容。
加在一起。
注意:在切片过程中,第一个索引是包含的,第二个索引是独占的
演示
一些解释:
通过切片,您可以获得列表的一部分。首先,请参见实际切片的工作原理:
lst[start:end:increment]
为了与您的问题相关,请跳过增量部分。默认增量为1,这正是我们需要的。因此,我们将切分如下列表:
lst[start:end]
让我们用给定的列表做一些实验
>>> test_list = [1, 28, 3, 4, 27, 5, 6, 7, 8]
比如说,我们想要一个从索引23到索引527的列表。简单地做:
>>> test_list[2:6]
[3,4,27]
>>test_list[3:]
[4, 27, 5, 6, 7, 8]
为什么我用6代替5。那是因为:
在切片的情况下,开始索引是包含的,但结束索引是独占的
如果我们想要一个从开始到索引427的列表呢。做:
>> test_list[:5]
[1,28,3,4,27]
如果我们想要索引3结束?简单地做:
>>> test_list[2:6]
[3,4,27]
>>test_list[3:]
[4, 27, 5, 6, 7, 8]
希望这会对您有所帮助。因为您实际上不需要知道哪个是哪个,您只需找到两个索引并切片即可
def triple_cut(lst):
first, second = [i for i, e in enumerate(lst) if e in [27, 28]]
return lst[second+1:] + lst[first:second+1]+ lst[:first]
我的代码只有在27和28之前和之后只有一个元素时才能正常工作。谢谢你的回答,事实上我对切片了解不多,所以你能给我一点切片的背景知识吗function@SyedNaqi,很高兴知道答案有帮助。但是,您可以查看更新后的答案以获得一些解释。