简体   繁体   English

具有特定规则的拆分列表

[英]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只需创建一个 3x3 列表,然后根据条件将项目附加到列表中

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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