1
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.

4 Answers 4

1

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])
Sign up to request clarification or add additional context in comments.

Comments

0
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']}

Comments

0

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']}

Comments

0

try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.