What do I try to do? Extract every 10 records of a given list and append it to another list. The main list can have 100.000 records or even more, I want to get 10 and 10 records then again more 10, etc.
how do I use a loop here to eliminate the need of A1..A10
? Also a more efficient replacement way for index 10
?
TEST = [
'AA',
'BB',
'CC',
'DD',
'EE',
'FF',
'GG',
'HH',
'II',
'JJ',
'11',
'22',
'33',
'44',
'55',
'66',
'77',
'88',
'99',
'10',
]
index = 0
while index < len(TEST):
A1 = TEST[index 0].rstrip('\n')
A2 = TEST[index 1].rstrip('\n')
A3 = TEST[index 2].rstrip('\n')
A4 = TEST[index 3].rstrip('\n')
A5 = TEST[index 4].rstrip('\n')
A6 = TEST[index 5].rstrip('\n')
A7 = TEST[index 6].rstrip('\n')
A8 = TEST[index 7].rstrip('\n')
A9 = TEST[index 8].rstrip('\n')
A10 = TEST[index 9].rstrip('\n')
index = index 10
accs_lst=[]
accs_lst.append(A1)
accs_lst.append(A2)
accs_lst.append(A3)
accs_lst.append(A4)
accs_lst.append(A5)
accs_lst.append(A6)
accs_lst.append(A7)
accs_lst.append(A8)
accs_lst.append(A9)
accs_lst.append(A10)
for i in accs_lst:
print(i)
CodePudding user response:
Use a loop inside your loop, and use extend
to append each item from the inner loop to your list without having to actually call append
ten times. You also probably want to move the accs_lst = []
, as noted:
accs_lst=[] # set this outside the loop so it doesn't get reset each time
for index in range(0, len(TEST), 10):
accs_lst.extend(a.rstrip('\n') for a in TEST[index:index 10])
for i in accs_lst:
print(i)
Note that given your sample input the rstrip
doesn't do anything, and given that you're just appending all the items to accs_lst
anyway there's no reason to do it in chunks of ten.
Assuming you did need to apply rstrip
to all the TEST
elements to produce accs_lst
, you could get rid of the chunk-by-ten thing and accomplish it more simply in a single line:
accs_lst = [a.rstrip('\n') for a in TEST]
If the idea is to do something with each distinct batch of ten items inside the loop, here's an example that makes it easier to see how that would work:
for index in range(0, len(TEST), 10):
accs_lst = [a "!" for a in TEST[index:index 10]]
print(*accs_lst)
which for your sample TEST input produces:
AA! BB! CC! DD! EE! FF! GG! HH! II! JJ!
11! 22! 33! 44! 55! 66! 77! 88! 99! 10!