python 中的切片列表

Slice list in python

我需要使用 python 3.7 对列表进行切片,切片应该包含两个元素,如果最后我们得到一个元素(如下所示),那么最后一个元素应该转到上一部分。

def solution(A):
    l = len(A)
    size = 2
    for i in range(1, len(A), size):
        print(A[i:i+2])

solution([4,2,2,5,1,5,8,9])  

输出:

[2, 2]
[5, 1]
[5, 8]
[9]

期望输出:

[2, 2]
[5, 1]
[5, 8, 9]

感谢您的帮助

def solution(A):
    l = len(A)
    size = 2
    for i in range(0, len(A), size):
        if l%2!=1 and i==l-3:  #if the length is odd and i is the third last
            print(A[i:i+3])
            break
        else:
            print(A[i:i+2])

solution([4,2,2,5,1,5,8,9])
def solution(A):
    l = len(A)
    size = 2
    groups = [ A[i:i+size] for i in range(1, len(A), size) ]
    if len(groups[-1]) < size:
       groups[-2].extend(groups.pop())
    for x in groups:
        print(x)

适用于大小的每个值,而不仅仅是 2。

您可以只检查下一个循环迭代是否会走得太远,如果是,则打印整个列表并停止。

喜欢

def solution(A):
    l = len(A)
    size = 2
    for i in range(1, len(A), size):
        print(i)
        if i+2*size > len(A):
            print(A[i:])
            break
        else:
            print(A[i:i+2])

这个函数可以解决问题(我对此不是很满意,而且我确信一定有更好的方法,但现在就可以了)。

def listSlicing(raw_list, slice_length):

    # Get the number of elements that will be left out when the list is sliced 
    extra_elements = len(raw_list)%slice_length 

    # Create a list of slices. Do not go to the last element
    sliced_list = [raw_list[i:i+slice_length] for i in range(0, len(raw_list)-extra_elements, slice_length)] 

    # Access the last item of the sliced list and append the extra elements to it
    if extra_elements == 0:
        return sliced_list # No need to change the last value
    else:
        sliced_list[-1].extend(raw_list[-extra_elements:]) 
        return sliced_list

l = [4,2,2,5,1,5,8,9,10]
listSlicing(l, 2)
# Will return [[4, 2], [2, 5], [1, 5], [8, 9, 10]]

如果一个切片只有 space(例如,假设 slice_length 为 5 而不是 2),该函数将 return 只有一个列表,如,在创建第一个切片之后,剩余的 4 个项目(5、8、9、10)将被附加到第一个切片本身,有效地再次 returning 相同的列表。

def func(a, size):
    c=[]
    if size==0 or size<0:
        return []
    if size>=len(a):
        return a 
    c = [a[i:i+size] for i in range(0,(len(a)//size)*size,size) if i%size==0] 
    c[-1].extend(a[(len(a)//size)*size:])
    return c

a = [4,2,2,5,1,5,8,9, 10]
print(func(a, 2))
print(func(a, 111))
print(func(a, 9))
print(func(a, 5))

输出

[[4, 2], [2, 5], [1, 5], [8, 9, 10]]
[4, 2, 2, 5, 1, 5, 8, 9, 10]
[4, 2, 2, 5, 1, 5, 8, 9, 10]
[[4, 2, 2, 5, 1, 5, 8, 9, 10]]