I'm asking if I can loop around the coding beginner list slice.

Asked 2 years ago, Updated 2 years ago, 137 views

I'd like to cut and print the bottom list combination of 5 pieces, so can you make the list slice range with a loop and make it automatically??

num = int(input())
moc = num//4
namu = num%4
like = 0
hell = 0
a = []

while like < moc:
    like = like + 1    
    hell = like    
    print(hell)    
    b=[]    
    b.append(hell)

    while hell < num:    
        hell = hell + moc    
        if hell > (num-namu): continue    
        print(hell)    
        b.append(hell)

    a.append(b)

hell = num - namu
b=[]
c=[]

while hell < num:
    hell = hell + 1    
    print(hell)    
    b.append(hell)

c.append(b)

# "List combination" in question
d=a[0:5]
print(d)
d=a[6:10]
print(d)
print(c)

python list slice loops

2022-09-20 14:24

2 Answers

I'm not sure what or how you want to do it, but if you just want to make a long list in a row into a list of lists with a specific length, you can do it in the term chunk.

# puom: https://stackoverflow.com/a/312464/8680764
def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

longlist = [1, 2, 'foo', 3, 'bar', 8876, 'dee', 'meh', -1, False, '1', None]

for five_items in chunks(longlist, 5) :
    print(five_items)


2022-09-20 14:24

Yeopto has already answered me, but... I think this is what you want, so I'm going to put it on for now.

a = list(range(50))
b = len(a)

for i in range(b)[::5]:
    print()
    for ii in range(5):
        print(a[i + ii])
>>>
0
1
2
3
4

5
6
7
8
9

Repeat below
for i in range(b)[::5]:
    print()
    print(a[i:i + 5])
>>> [0, 1, 2, 3, 4]

[5, 6, 7, 8, 9]

[10, 11, 12, 13, 14]

[15, 16, 17, 18, 19]

Repeat below


2022-09-20 14:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.