简体   繁体   中英

How to get the perform a difference in each sublist of a list?

I want to create a list that would be the difference between the last and the first element of each sublist of a list. Sublists are sublists of N elements, so I will have len(list)/K+1 elements in my final list.


Here is a little example:

I have a list : [0, 10, 20, 5, 10, 30, 20, 35] . I chose to have a maximum of 3 elements per sublist. I will have the following sublists [0, 10, 20], [5, 10, 30], [20, 35] .

Now I apply the difference in each sublist and I get the values 20, 25, 15 (because 20-0 , 30-5 and 35-20 ).

I want the result to be in a list, so to have [20, 25, 15] as a final result.

As requested in the original version of the question, and according to the edits made by the OP, we create a list of increasing sequences, then calculate the differences between the max and min of each of them:

def spans(data):
    sequences = [[data[0]]]

    for val in data[1:]:
        if val >= sequences[-1][-1]:
            sequences[-1].append(val)
        else:
            sequences.append([val])

    return [s[-1] -s[0] for s in sequences]

Sample run with the OP's data:

data = [0, 10, 20, 5, 10, 30, 20, 35]
print(spans(data))
# [20, 25, 15]

Another one:

print(spans([2, 4, 6, 8, 9, 4, 5, -2, -1, 5, 4]))
# [7, 1, 7, 0]

Here is a script that should help you.

Care if you have only one element in the last sublist, I don't know how you want to deal with this case. I considered that the element is the result of this sublist, but maybe you want to ignore the last sublist or to have 0 as a result.

Explanations are the comments in the script:

# Initial list
l = [0, 10, 20, 5, 10, 30, 20, 35]

# Number of elements to consider in each sublist.
STEP = 3

# Get the size of the list
length = len(l)

# The result list, empty at the beginning, that will be populated by the differences
result_list = []

# Iterate through sublists of exactly STEP elements
i = 0
while (i+STEP-1)<length:
    result_list.append(l[i+STEP-1]-l[i])
    i += STEP

# Special case for the possible little last sublist
# No difference done and element is kept if there is only one element
if i==length-1:
    result_list.append(l[-1])
# Else, do the difference in the last sublist
elif i<length-1:
    result_list.append(l[-1]-l[i])

Here is the script that takes the max-min of each sublist, as OP asked primarily:

l = [1,2,3,4,5,6,7,8]
n = 3

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

# Create the sublists
grouped_l = list(chunks(l,n))

# Do the max-min on each sublists
res = []
for i in grouped_l:
    res.append(max(i)-min(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM