使用特定规则拆分列表

时间:2019-04-29 15:25:36

标签: python list

我想基于循环创建子列表,但是仍然找不到执行该操作的逻辑?

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

4 个答案:

答案 0 :(得分:0)

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)

输出:

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

答案 1 :(得分:0)

只需创建一个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)

输出看起来像

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

答案 2 :(得分:0)

除了其他人发布的内容之外,您还可以创建一个字典,其中以列表名称为键,以列表名称为值,如下所示:

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

答案 3 :(得分:0)

有人认为吗?

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

一个循环看起来像这样

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