Home > Enterprise >  create multiple list from a list taking every nth item using for loop in python
create multiple list from a list taking every nth item using for loop in python

Time:11-24

test_list=['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13','a14','a15','a16','a17','a18']

my_result=
{'list_a': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],'list_b': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],'list_c': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}

here is a example of test_list and my_result. i want to create multiple lists from a list taking every nth item using for loop in python. I tried but failed. Can anyone help me solving this probem? thanks in advance.

CodePudding user response:

You can use mod:

list_a = []
list_b = []
list_c = []


for i in range(len(test_list)):
    if i % 3 == 0:
        list_a.append(test_list[i])
    if i % 3 == 1:
        list_b.append(test_list[i])
    if i % 3 == 2:
        list_c.append(test_list[i])

CodePudding user response:

num_list = 3

out = dict(zip([f'list_{i}' for i in range(1, num_list 1)], [[test_list[j] for j in range(i, len(test_list), num_list)] for i in range(num_list)]))

# {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],
#  'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],
#  'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}

CodePudding user response:

you can do the following and generalize your code using a function

def reorder_list(original_list, interval):
    return {f"list_{i 1}":  original_list[i::interval] for i in range(interval)}

reorder_list(test_list, 3)     
>>> {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],
 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],
 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}

CodePudding user response:

try this:

result={}
for i in range (0,n):
    result[f"list_{i}"]=test_list[i::n]
  • Related