Home > Enterprise >  How can I obtain the elements in a single list with specified indices?
How can I obtain the elements in a single list with specified indices?

Time:06-06

Suppose I have a list

li = ['a0','b0','c0','a1','b1','c1',...,'an','bn','cn']

I want to obtain

['a0',...,'an'], ['b0',...,'bn'], ['c0',...,'cn']

using a for loop. I'm trying to do something like

for i in range(3): # for a,b,c
    lis = [li[i][k] for i in range(n 1)] # Hope to get [a0,...,an], etc
    print(lis)

However, this method won't work because there's no sublist here. I don't think I can do something like i*k because the indices start at 0. How can I obtain the desired output?

CodePudding user response:

You can just create different slices:

count = 3 
main_list = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'an', 'bn', 'cn']

for i in range(count):
    sub_list = main_list[i::count]
    
    print(sub_list)

Or use a list comprehension if you want to create a list of sublists:

count = 3
main_list = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'an', 'bn', 'cn']
sub_lists = [main_list[i::count] for i in range(count)]

print(sub_lists)

CodePudding user response:

Consider li[::3], li[1::3], li[2::3].

You can use the powerful Python slicing facility.

print(li[::3]) would print ['a0','a1',...,'an']

print(li[1::3]) would print ['b0','b1',...,'bn']

print(li[2::3]) would print ['c0','c1',...,'cn']

In Python slice notation [x:y:z] means take a slice from x to y skipping z-1 elements in between, i.e. take elements with indices x, x z, up to but not including y

  • Related