[英]How to separate Consecutive and Non consecutive number from a python list
Input: lst = [101,102,103,104,120,131,132,133,134]输入:lst = [101,102,103,104,120,131,132,133,134]
Expected output: consecutive - [101,102,103,104,131,132,133,134] non consecutive = [120]预期输出:连续 - [101,102,103,104,131,132,133,134] 非连续 = [120]
def first_consecutive(lst):
a = []
for i,j in enumerate(lst,lst[0]):
if i!=j:
a.append(j)
return a
Any suggestion?有什么建议吗?
You can just keep a list as you loop through the (sorted) numbers.您可以在遍历(排序的)数字时保留一个列表。 When you encounter something that's consecutive, add it to the list.当您遇到连续的内容时,请将其添加到列表中。 Otherwise put the values in the right place and redefine the list.否则,将值放在正确的位置并重新定义列表。 Easier to show than explain:展示比解释更容易:
l = [101,102,103,104, 120,131,132,133,134]
def partition_groups(l):
out = [[], []]
current = [l[0]]
for n in l[1:]:
if current[-1] + 1 == n:
current.append(n)
else:
out[len(current) > 1].extend(current)
current = [n]
out[len(current) > 1].extend(current)
return out
nonconsecutive, consecutive = partition_groups(l)
print(nonconsecutive)
# [120]
print(consecutive)
# [101, 102, 103, 104, 131, 132, 133, 134]
This?这个? (assumes list is already sorted, if not just call lst.sort()
first) (假设列表已经排序,如果不是先调用lst.sort()
)
(Simply compare each element to its previous (if any) and next (if any) neighbour.) (只需将每个元素与其前一个(如果有)和下一个(如果有)邻居进行比较。)
consec = []
non_consec = []
L = len(lst)
for i in range(L):
if i>0 and lst[i-1]==lst[i]-1 or i<L-1 and lst[i+1]==lst[i]+1:
consec.append(lst[i])
else:
non_consec.append(lst[i])
You could do something like this你可以做这样的事情
def sort_list(list):
sorted_list = []
non_consecutive_list = []
for i in range(len(list)):
if list[i] + 1 in list or list[i] - 1 in list:
sorted_list.append(list[i])
else:
non_consecutive_list.append(list[i])
return sorted_list, non_consecutive_list
num_list = [101,102,103,104,120,131,132,133,134]
sorted_list, non_consecutive_list = sort_list(num_list)
print(sorted_list, non_consecutive_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.