我有一个元素列表,我需要循环地重新排列,以便保持它们的顺序。这个问题看起来很简单,但我想不出一个聪明的方法来编码它。假设你有元素
1 2 3 4 o o o 5 6 7
o在数组中总是连续的,但我需要更改此数组,以便o(不一定是不同类型的)以循环方式位于最后:
5 6 7 1 2 3 4 o o o
问题是o也可能以循环方式连续。例如
o o 1 2 3 4 5 6 7 o
有什么聪明的方法吗?我一直在研究itertools中的cycle
,但到目前为止,我还没有一个有效的实现,因为我所做的无法处理最后一个案例。你知道吗
更新
我有一个第一个工作实现:
def arrange2(nodes, contiguous):
arranged = []
size = len(nodes)
if nodes[0] in contiguous:
# obtain the id of the last interface node in nodes
id = None
for i in range(1, len(nodes)):
if nodes[i] not in contiguous:
id = i
break
# copy nodes to new list starting from the first node past id
for i in range(id, id + size):
arranged += [nodes[i % size]]
else:
# obtain the id of the last interface node in nodes
id = None
for i in range(size - 1, -1, -1):
if nodes[i] in contiguous:
id = i
break
# copy nodes to new list starting from the first node past id
for i in range(id+1, id + size+1):
arranged += [nodes[i % size]]
return arranged
print(arrange2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [5, 6]))
这个指纹 [7,8,9,10,1,2,3,4,5,6]
利用所有“o”都是连续的这一事实,我实现了:
您可以遍历列表。在第一次出现
i
一个“o”时,您可以拆分列表并反转它。l=["o","o",1,2,3,"o"]
在["o"] (l[:i+1])
和["o",1,2,3,"o"] (l[i+1:])
中被“拆分”。把这两部分颠倒过来,再把它们放在一起,就得到了一个新的列表["o",1,2,3,"o","o"]
。这样,“o”就被推到了最后。你知道吗
然后从新列表开始。当新列表不是以“o”开头时(
found
为True,l[i]!="o"
),表示您的任务完成了。你知道吗要提供连续元素的列表而不是“o”,这个小小的更改应该有效:
好的,根据你的执行情况,我有:
在评论中澄清后,编辑连续收藏不必订购我有:
注意:这是你的工作,以确保连续的元素确实是紧挨着对方,而不是分散在3个或更多组。你知道吗
相关问题 更多 >
编程相关推荐