简体   繁体   中英

split list with specific rules

I want to create sublist based on looping, but still not find the logic on how to do it?

''' source list'''
list = [1,2,3,4,5,6,7,8,9]
''' sublist goals'''
list_1 = [1,4,7]
list_2 = [2,5,8]
list_3 = [3,6,9]
list = [1,2,3,4,5,6,7,8,9]

list_1 = []
list_2 = []
list_3 = []

for j in range(1,4):
    for i in range(j,len(list)+1,3):
        if j == 1:
            list_1.append(i)
        if j == 2:
            list_2.append(i)
        if j == 3:
            list_3.append(i)

print (list_1)
print (list_2)
print (list_3)

output:

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

Just create a 3x3 list and then append items to the list according to the condition

li = [1,2,3,4,5,6,7,8,9]

#Create a 3x3 list
res = [ [] for _ in range(3)]

for idx in range(len(li)):
    #Append elements accordingly
    index = int(idx%3)
    res[index].append(li[idx])

print(res)

The output will look like

[[1, 4, 7], 
[2, 5, 8], 
[3, 6, 9]]

In addition to what others have posted you could create a dictionary with the name of the list as the key and the list as the values like this:

>>> for i in range(3):
...   d["list_{}".format(i)] = [list[i], list[i+3], list[i+6]]
... 
>>> d
{'list_2': [3, 6, 9], 'list_1': [2, 5, 8], 'list_0': [1, 4, 7]}```

Did any one consider this?

>>> list=[1,2,3,4,5,6,7,8,9]
>>> list_1 = list[0::3]
>>> list_2 = list[1::3]
>>> list_3 = list[2::3]
>>> list_1
[1, 4, 7]
>>> list_2
[2, 5, 8]
>>> list_3
[3, 6, 9]

A loop would look like this

for i in range(0,3):
    list_i = list[i::3]
    print(list_i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM