輸入總是嚴格增加的。我可以用一個 for 回圈和許多 if-else 條件來寫這個,但是有一些簡單的方法嗎?這是一個例子:
input: [2,3,4,6,8,9]
output: [[0,1,2],[4,5]]
input: [1,2,3,4]
output: [[0,1,2,3]]
input: [0,1,2,4,6,7,8,10,12,13,14]
output: [[0,1,2], [4,5,6], [8,9,10]]
例如這里是我寫的代碼
def get_mergable_indices(sent_order):
mergable_indices = []
continuous_sents = [0]
for index, value in enumerate(sent_order):
if index == 0:
continue
else:
if value - sent_order[index-1] == 1:
continuous_sents.append(index)
else:
if len(continuous_sents)>1:
mergable_indices.append(continuous_sents)
continuous_sents = [index]
if len(continuous_sents)>1:
mergable_indices.append(continuous_sents)
return mergable_indices
太大了想減
uj5u.com熱心網友回復:
這可以在不使用任何模塊的情況下輕松完成。
def get_mergable_indices(sent_order):
lst = sent_order
out = []
l = []
for a in range(max(lst)): # set range to the max number in the list.
try:
if lst[a] 1 == lst[a 1]: # check current number plus 1 is equal to next number
l.append(a)
l.append(a 1)
else: # if not equal then append l to the out list also set the l to an empty list.
if l:
out.append(list(set(l)))
l = []
except IndexError:
pass
out.append(list(set(l)))
return (out)
輸出
input: [2,3,4,6,8,9]
output: [[0,1,2],[4,5]]
input: [1,2,3,4]
output: [[0,1,2,3]]
input: [0,1,2,4,6,7,8,10,12,13,14]
output: [[0,1,2], [4,5,6], [8,9,10]]
uj5u.com熱心網友回復:
這可以接受任何可迭代的序列:
from itertools import pairwise
def get_mergable_indices(sent_order):
result = []
curr = []
for idx, (i, j) in enumerate(pairwise(sent_order)):
if j - i == 1:
curr.append(idx)
elif curr:
curr.append(idx)
result.append(curr)
curr = []
if curr:
curr.append(idx 1)
result.append(curr)
return result
輸出:
>>> get_mergable_indices([2, 3, 4, 6, 8, 9])
[[0, 1, 2], [4, 5]]
>>> get_mergable_indices(range(1, 5))
[[0, 1, 2, 3]]
>>> get_mergable_indices([0, 1, 2, 4, 6, 7, 8, 10, 12, 13, 14])
[[0, 1, 2], [4, 5, 6], [8, 9, 10]]
uj5u.com熱心網友回復:
這是我的方法:
inp = [0,1,2,4,6,7,8,10,12,13,14]
idx = idy = 0
res = [[]]
while idx < len(inp) - 1:
# Not append repeated indices
if inp[idx] - inp[idx 1] == -1: # If the next element is 1 higher, just check for -1
if idx not in res[idy]:
res[idy].append(idx)
if idx 1 not in res[idy]:
res[idy].append(idx 1)
else:
# Don't append empty lists
if len(res[idy]):
res.append([])
idy = 1
idx = 1
print(res)
我認為這可以大大改善
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/467419.html
上一篇:編碼布爾邏輯時出現未知語法錯誤
