2017-03-14 284 views
-3

假设我有一个列表['slide-1','slide-2','slide-3','slide-5','slide -6'],我想将它分成两个列表['slide-1','slide-2','slide-3']和['slide-5','slide-6']。Python如何在条件不同的情况下分割列表

逻辑是当序列1,2,...,N被中断时打破列表。 所以在这里我会打破3,因为它后面是5,而不是4.

我该如何解决这个问题?

+0

在何种条件下,拆分列表。你是否试图将不平的列表分成两份,第一份列表是两个列表中较大的一份?你需要更具体。 –

+0

是的我试图划分一个不规则的列表,并且第一个列表更大 –

+0

[将任意大小的列表拆分为大致N-等份的部分](http://stackoverflow.com/questions/2130016/splitting- a-list-of-arbitrary-into-only-approximate-n-equal-parts) – gavv

回答

0

这里是一个相当普遍的做法:

or_list = ['slide-1','slide-2','slide-3', 'slide-5','slide-6'] 

# Isolate Values from list 
values_list = [int(el.split("-")[-1]) for el in or_list] 

# Determine where the gaps are occurring 
gap_loc = [idx + 1 
      for (idx, el), next_el in zip(enumerate(values_list[:-1]), values_list[1:]) 
      if (next_el - el) > 1] 

# Adding beginning and end of the list 
gap_loc.insert(0, 0) 
gap_loc.append(len(or_list)) 

# Create sublists where gaps occurs 
list_seq = [or_list[prev_gap:gap] for prev_gap, gap in zip(gap_loc[:-1],gap_loc[1:])] 

# [['slide-1', 'slide-2', 'slide-3'], ['slide-5', 'slide-6']] 
相关问题