简体   繁体   English

如何在 Python 中将列表划分为交替大小的块?

[英]How to divide a list into chunks of alternating sizes in Python?

I need to divide a string into chunks of unequal sizes, that is,if in a for loop i meets a certain condition then the chunk should be of specific length otherwise of different length.我需要将一个字符串分成大小不等的块,也就是说,如果在 for 循环中我满足某个条件,那么该块应该具有特定的长度,否则具有不同的长度。 Basically I need to create a 2d array(list) where I know the number of rows but don't know the number of columns as the length of string is unknown.基本上我需要创建一个二维数组(列表),我知道行数但不知道列数,因为字符串的长度是未知的。 I tried various methods on googling.我尝试了各种谷歌搜索方法。 Here is one I tried on own.这是我自己尝试过的一个。

    a = [1,2,3,4,5,6,7,8]
b = []
c=[]
def divide_chunks(l): 
      
    # looping till length l 
    for i in range(0, len(l)):
        j = 0
        if(i%2==0):
           while(j<4 and i<=len(l)):
               b.append(l.pop())
               i = i+1
        else:
              while(j<2 and i<=len(l)):
               b.append(l.pop())
               i = i+1
        c.append(b)    

The problem I am facing is that the numbers or lets say words in case of string are getting overlapped in each chunk.我面临的问题是数字或让我们说的字符串在每个块中都重叠。 For example one of the output is例如 output 之一是

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

So I want to achieve something like if string is markisgoodboy.所以我想实现类似 if string is markisgoodboy。 Then for first row it will take "mark" second row "is" and third row "good" and fourth row "bo" and last row "y".然后对于第一行,它将采用“mark”第二行“is”和第三行“good”,第四行“bo”和最后一行“y”。 Please take note that it is row wise.请注意,它是按行排列的。 The length of rows will be supplied as an argument for every method call.行的长度将作为每个方法调用的参数提供。 How to solve it?如何解决? Thanks:)谢谢:)

This should work for both, lists and strings that don't contain empty elements:这应该适用于不包含空元素的列表和字符串:

def chunks(s, m, n):
    s1 = [s[i:i+m] for i in range(0, len(s), m+n)] 
    s2 = [s[i+m:i+m+n] for i in range(0, len(s), m+n)] 
    return [e for t in zip(s1, s2) for e in t if e]

s = '1234567890ABCDEFGHIJKLMNO'
m = 4
n = 2

print(chunks(list(s), m, n))
print(chunks(s, m, n))

Sample output:样品 output:

[['1', '2', '3', '4'], ['5', '6'], ['7', '8', '9', '0'], ['A', 'B'], ['C', 'D', 'E', 'F'], ['G', 'H'], ['I', 'J', 'K', 'L'], ['M', 'N'], ['O']]
['1234', '56', '7890', 'AB', 'CDEF', 'GH', 'IJKL', 'MN', 'O']

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

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