2

我有一个如下所示的列表。

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

我想把它分成三个列表,这些列表将具有以下值。

first_list = [1, 4, 7, ...]
second_list = [2, 5, 8,....]
third_list = [3, 6, 9, ...]

我不想将其拆分为三个大小相等的块,并且希望将列表按上述方式拆分。任何帮助都是有用的。

谢谢

4

6 回答 6

7

通过更改起始值和设置步长值来使用切片表示法:

l[start:end:step] 

In [1]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]: [l[start::3] for start in range(3)]
Out[2]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

要将列表分配给变量:

first_list, second_list, third_list = [l[i::3]for i in range(3)]
于 2013-05-13T18:48:35.463 回答
5
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print (my_list[0::3])
print (my_list[1::3])
print (my_list[2::3])

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

另外,永远不要使用 list 作为变量名。在您知道自己在做什么之前,请将“my”放在所有变量名的前面。

于 2013-05-13T18:48:39.530 回答
3

我不确定这是否是您想要的,但它确实为您提供了您要求的输出,所以:

首先,使用食谱grouper中的功能:itertools

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
groups = grouper(lst, 3)
a, b, c = zip(*groups)

如果您了解其grouper工作原理,它只是将 3 个迭代器的副本压缩在一起lst,因此您可以将其简化为:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
it = iter(lst)
a, b, c = zip(*zip(it, it, it))
于 2013-05-13T18:48:18.837 回答
1
my_list = range(10)
def condition1(x):
    return x%3 == 1

def condition2(x):
    return x%3 == 2

L1,L2,L3 = [],[],[]
#[L1.append(x) if condition1(x) else L2.append(x) if condition2(x) else L3.append(x) for x in my_list]
#made above list comprehension more readable by switching it to a for loop
for item in list:
    if condition1(item): 
         L1.append(item)
    elif condition2(item):
         L2.append(item)
    else:
         L3.append(item)
print L1
print L2
print L3
于 2013-05-13T18:48:32.690 回答
1

对于大小不一的组,您可以将序列垂直分配到n许多单独的列表中,并使用哨兵值将剩余的列表留给比值更短的列表n...

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

from itertools import izip_longest
sentinel = object()
grouped = zip(*izip_longest(*[iter(lst)] * 3, fillvalue=sentinel))
list1, list2, list3 = ([el for el in obj if el is not sentinel] for obj in grouped)
print list1, list2, list3
# [1, 4, 7] [2, 5, 8] [3, 6]
于 2013-05-13T18:53:33.667 回答
0

您是否希望它们根据索引或元素值进行拆分?

如果它是按元素值,你可以做这样的事情(使用模数三过滤):

list = range(1,10)

first_list = filter(lambda x: x % 3 == 1, list)
second_list = filter(lambda x: x % 3 == 2, list)
third_list = filter(lambda x: x % 3 == 0, list)

如果是按索引,则使用切片表示法:

list = range(1,10)

first_list = list[::3]
second_list = list[1::3]
third_list = list[2::3]

查看有关过滤器lambda 的文档(以及其他很棒的内置函数)。

于 2013-05-13T19:00:05.873 回答