195

我正在寻找一种轻松将 python 列表分成两半的方法。

所以如果我有一个数组:

A = [0,1,2,3,4,5]

我将能够得到:

B = [0,1,2]

C = [3,4,5]
4

19 回答 19

293
A = [1,2,3,4,5,6]
B = A[:len(A)//2]
C = A[len(A)//2:]

如果你想要一个功能:

def split_list(a_list):
    half = len(a_list)//2
    return a_list[:half], a_list[half:]

A = [1,2,3,4,5,6]
B, C = split_list(A)
于 2009-04-15T15:49:42.240 回答
96

更通用的解决方案(您可以指定所需的零件数量,而不仅仅是“分成两半”):

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
             for i in range(wanted_parts) ]

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

print split_list(A, wanted_parts=1)
print split_list(A, wanted_parts=2)
print split_list(A, wanted_parts=8)
于 2009-04-15T16:30:41.957 回答
47
f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)

n- 结果数组的预定义长度

于 2010-02-07T02:30:56.317 回答
40
def split(arr, size):
     arrs = []
     while len(arr) > size:
         pice = arr[:size]
         arrs.append(pice)
         arr   = arr[size:]
     arrs.append(arr)
     return arrs

测试:

x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(split(x, 5))

结果:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]
于 2014-04-18T06:54:33.170 回答
20

如果你不关心订单...

def split(list):  
    return list[::2], list[1::2]

list[::2]从第 0 个元素开始获取列表中的每个第二个元素。
list[1::2]从第一个元素开始获取列表中的每个第二个元素。

于 2011-06-13T09:11:54.880 回答
13

使用列表切片。语法基本上是my_list[start_index:end_index]

>>> i = [0,1,2,3,4,5]
>>> i[:3] # same as i[0:3] - grabs from first to third index (0->2)
[0, 1, 2]
>>> i[3:] # same as i[3:len(i)] - grabs from fourth index to end
[3, 4, 5]

要获取列表的前半部分,请从第一个索引切片到len(i)//2//整数除法在哪里 - 所以3//2 will give the floored result of1 , instead of the invalid list index of1.5`):

>>> i[:len(i)//2]
[0, 1, 2]

..并交换周围的值以获得下半部分:

>>> i[len(i)//2:]
[3, 4, 5]
于 2009-04-15T16:28:30.667 回答
11

B,C=A[:len(A)/2],A[len(A)/2:]

于 2009-04-15T15:50:08.947 回答
11

这是一个常见的解决方案,将 arr 拆分为 count 部分

def split(arr, count):
     return [arr[i::count] for i in range(count)]
于 2012-07-20T07:17:29.403 回答
9
def splitter(A):
    B = A[0:len(A)//2]
    C = A[len(A)//2:]

 return (B,C)

我测试过,在 python 3 中强制 int 除法需要双斜杠。我原来的帖子是正确的,尽管由于某种原因,所见即所得在 Opera 中中断了。

于 2009-04-15T15:49:40.807 回答
7

如果您有一个大列表,最好使用itertools并编写一个函数来根据需要生成每个部分:

from itertools import islice

def make_chunks(data, SIZE):
    it = iter(data)
    # use `xragne` if you are in python 2.7:
    for i in range(0, len(data), SIZE):
        yield [k for k in islice(it, SIZE)]

您可以像这样使用它:

A = [0, 1, 2, 3, 4, 5, 6]

size = len(A) // 2

for sample in make_chunks(A, size):
    print(sample)

输出是:

[0, 1, 2]
[3, 4, 5]
[6]

感谢@thefourtheye@Bede Constantinides

于 2018-12-30T09:10:44.623 回答
6

对于将数组拆分为更小的 size 数组的更一般化的情况,有一个官方的 Python 收据n

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

此代码片段来自python itertools 文档页面

于 2011-04-21T21:44:10.557 回答
6

这与其他解决方案类似,但速度更快。

# Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5])

def split_half(a):
    half = len(a) >> 1
    return a[:half], a[half:]
于 2014-05-27T17:17:30.603 回答
3

10 年后.. 我想 - 为什么不添加另一个:

arr = 'Some random string' * 10; n = 4
print([arr[e:e+n] for e in range(0,len(arr),n)])
于 2019-02-26T19:22:29.990 回答
2

虽然上面的答案或多或少是正确的,但如果你的数组的大小不能被 2 整除,你可能会遇到麻烦,因为a / 2,a 是奇怪的,是 python 3.0 中的浮点数,如果你在早期版本中from __future__ import division在脚本的开头指定。无论如何,您最好进行整数除法,即a // 2,以获得代码的“前向”兼容性。

于 2009-04-15T19:03:34.037 回答
1
#for python 3
    A = [0,1,2,3,4,5]
    l = len(A)/2
    B = A[:int(l)]
    C = A[int(l):]       
于 2017-10-05T20:43:02.223 回答
0

来自@ChristopheD 的提示

def line_split(N, K=1):
    length = len(N)
    return [N[i*length/K:(i+1)*length/K] for i in range(K)]

A = [0,1,2,3,4,5,6,7,8,9]
print line_split(A,1)
print line_split(A,2)
于 2012-08-02T04:24:25.720 回答
0

2020 年对这个问题的另一种看法……这是对这个问题的概括。我将“将列表分成两半”解释为..(即只有两个列表,并且在出现奇数的情况下不会溢出到第三个数组等)。例如,如果数组长度为 19,使用 // 运算符除以 2 得到 9,我们最终将得到两个长度为 9 的数组和一个长度为 1 的数组(第三个)(所以总共三个数组)。如果我们想要一个始终提供两个数组的通用解决方案,我会假设我们对长度不相等的结果双数组感到满意(一个会比另一个长)。并且假设可以混合顺序(在这种情况下交替)。

"""
arrayinput --> is an array of length N that you wish to split 2 times
"""
ctr = 1 # lets initialize a counter

holder_1 = []
holder_2 = []

for i in range(len(arrayinput)): 

    if ctr == 1 :
        holder_1.append(arrayinput[i])
    elif ctr == 2: 
        holder_2.append(arrayinput[i])

    ctr += 1 

    if ctr > 2 : # if it exceeds 2 then we reset 
        ctr = 1 

这个概念适用于你想要的任何数量的列表分区(你必须根据你想要的列表部分调整代码)。并且解释起来相当简单。为了加快速度,您甚至可以在 cython / C / C++ 中编写这个循环来加快速度。再说一次,我在相对较小的列表上尝试了这段代码 ~ 10,000 行,它在几分之一秒内完成。

只是我的两分钱。

谢谢!

于 2020-05-28T05:04:23.200 回答
0

通用解决方案将列表拆分为 n 部分并进行参数验证:

def sp(l,n):
    # split list l into n parts 
    if l: 
        p = len(l) if n < 1 else len(l) // n   # no split
        p = p if p > 0 else 1                  # split down to elements
        for i in range(0, len(l), p):
            yield l[i:i+p]
    else:
        yield [] # empty list split returns empty list
于 2021-04-26T06:22:25.617 回答
0
from itertools import islice 

Input = [2, 5, 3, 4, 8, 9, 1] 
small_list_length = [1, 2, 3, 1] 

Input1 = iter(Input) 

Result = [list(islice(Input1, elem)) for elem in small_list_length] 

print("Input list :", Input) 

print("Split length list: ", small_list_length) 

print("List after splitting", Result)
于 2021-10-22T17:04:37.533 回答