Python Multiple List Divide Questions

Asked 2 years ago, Updated 2 years ago, 114 views

I posted the same question a few days ago and I'll ask you one more time.

def random_chunk(li, min_chunk=1, max_chunk=3):

    it = iter(li)
    while True:
        nxt = list(islice(it,randint(min_chunk,max_chunk)))
        if nxt:
            yield nxt
        else:
            break

li = [ 1, 2, 3, 4, 5]
b = [5,6,7,8,9]

divide = list(random_chunk(li))
d = []
for i in divide:
    cut = len(i)
    ad = b[:cut]
    d.append(ad)
print d

#Current print
[[1, 2], [3, 4, 5]]
Must be [[5, 6], [5, 6, 7] -> [[5, 6], [7, 8, 9]]

The above code is currently a function I made, and when the first list li is divided by the function random_chunk, I tried it because I thought it would be divided equally if I received the length of each list using the for statement and applied it to another list. However, if you follow the code above, the list of b is divided into the same list as the list of li, but the elements are duplicated. How can I make sure that there is not duplicated?

python python-2.7

2022-09-21 17:32

1 Answers

d = []
p = 0
for i in divide:
    cut = len(i)
    ad = b[p:p+cut]    
    d.append(ad)
    p += cut
print(d)

Results

[[1, 2], [3], [4, 5]]
[[5, 6], [7], [8, 9]]

It's not a very good code, but I solved it with minimal modification.


2022-09-21 17:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.