Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

separating a list into two separate list in python

This is my list

lis = [['For the first', '$7.56'], ['For the next', '$16.69'],
['For the first', '$18.34'], ['For the next', '$43.47']]

In this there will always be 2 "for the first" and N times "for the next" for example;-

lis = [['For the first', '$7.56'], ['For the next', '$16.69'],['for the next','$3.4'],['for the next','$2'],['For the first', '$18.34'], ['For the next', '$43.47'],[for the next,'$34']

I want to separate list into 2.

1:from 1st "for the first" to 2nd 'for the first'(not included)
2: from 2nd 'for the first'(included) to last element

delivery=[]
supply=[]

for j in range(1,len(lis)):
    
    if(lis[j][0].lower()=='for the first'):
        
        break
    else:
         delivery.append(lis[j][1])

print(delivery)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If it can be guaranteed that there will be two items in the list with 'for the first' in index 0, would do it like this:

lst = [['For the first', '$7.56'], ['For the next', '$16.69'],
['For the first', '$18.34'], ['For the next', '$43.47']]

lst_first = []
for i, item in enumerate(lst):
    if item[0].lower() == 'for the first':
        next_occurence = next(j for j, item in enumerate(lst[i+1:], 1) if item[0].lower()=='for the first')
        lst_first = lst[i+1:next_occurence]
        lst_other = lst[next_occurence:]
        break

which produces:

print(lst_first)  # [['For the next', '$16.69']]
print(lst_other)  # [['For the first', '$18.34'], ['For the next', '$43.47']]

Explanation

The way this works is that it uses a simple for loop as in your code to find the first instance of 'for the first' and then next to find the second one. The second search with next does not search the entire list but rather the slice of it starting from the element after the first instance. When the two instances are found, the resulting lists are assembled as slices of the first one. After that, we break out of the for loop.

P.S

whether you need the lower() calls or not I will leave up to you. Just note that it is redundant if your input is always consistent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...