如何解决Python组列表到子列表的列表是单调的,元素之间的差异相等
l = [2,4,6,12,14,16,21,27,29,31]
我想将其拆分为列表,以便每个列表的元素都是单调列表,元素之间的差异为2:
new_l = [[2,6],[12,16],[21],[27,31]]
最有效的方法是什么?
解决方法
更新
可以完全避免Python循环,而仅使用comprehensions
(以及zip
)可以提高效率。您可以按照以下步骤进行操作:
l = [2,4,6,12,14,16,21,27,29,31,44]
n = len(l)
#Find the splitting points (where the monotonic condition breaks):
splitting_points = [0] + [k for k in range(1,n) if l[k] - l[k - 1] != 2]
if splitting_points[-1] != n:
splitting_points.append(n)
#Then split the list into intervals having bounds in the splitting_points:
new_l = [l[i: j] for i,j in zip(splitting_points[:-1],splitting_points[1:])]
print(new_l)
这个“应该”比循环要快得多(尤其是对于大型列表),但是我还没有做任何基准测试。
原始
您必须遍历初始列表l
,维护一个具有当前单调序列的当前列表,并且每当新的迭代元素打破单调条件时,就插入当前列表并清除它。
这是完全符合此要求的代码:
l = [2,31]
new_l = []
current_l = [l[0]] #initially,insert the first element
for k in range(1,len(l)):
if l[k] - current_l[-1] == 2: #if the monotonic condition is satisfied
current_l.append(l[k]) #we append the element
else:
new_l.append(current_l) #otherwise,we append the previous list to the answer
current_l = [l[k]] #and clear the running sequence
new_l.append(current_l) #there will always be a last sequence not appended to the answer
print(new_l)
,
您可以标识要在哪里分割的索引,然后像下面这样应用const byUpvotes = () => {
const sortByName = [...dummyData];
sortByName.sort((a,b) => {
return b.upvotes - a.upvotes
})
setDummyData(sortByName)
}
:
np.split
输出:
np.split(l,np.flatnonzero(np.diff(l)!=2) + 1)
但是,玩不同长度的数组从来没有效率,所以这就是[array([2,6]),array([12,16]),array([21]),array([27,31])]
很慢的原因。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。