iT邦幫忙

1

python list切分問提

我想要切分下列的list,當某個項超過一定字數後要變為下一項,但要切在最靠近中間的逗號

paragraph = [['今天適合出門','你,我,他他她'],['一二三,四五六七,八,九十']]

#當某項超過6個字後我想將它切分,但我想切分在該項,切分完後變成

paragraph = [['今天適合出門','你,我','他他她'],['一二三','四五六七','八,九十']]

#一二三,四五六七由於還是超過六個字所以在切一次

功力不佳只想到split切字串,但卻又不知道如何下手

for i in range (0,len(paragraph):
    a = 0
    for j in range(0,len(paragraph[i])):
        a = len(paragraph[i][j])
        while a >6:
            #print(a,i,j)

不知道照這方向寫下去可不可行,求求各位大師們幫忙了

2 個回答

0
lutrainee
iT邦新手 5 級 ‧ 2021-10-28 00:20:32
paragraph = [['今天適合出門','你,我,他他她'],['一二三,四五六七,八,九十']]

alist =[[],[]]
alist[0] = list(paragraph[0][0] + paragraph[0][1])
alist[1] = list(paragraph[1][0])

result =[[],[]]
x = 0
while x < 2:
    
    n = divmod(len(alist[x]), 6)
    
    if n[1] != 0:
        for i in range(n[0]+1):
            element = ""
            for idx,item in enumerate(alist[x]):
                if idx < 6:
                    element += item
            result[x].append(element)
            del alist[x][0:6]
            
        x += 1
    else:
        n[1] == 0
        for i in range(n[0]):
            element = ""
            for idx,item in enumerate(alist[x]):
                if idx < 6:
                    element += item
            result[x].append(element)
            del alist[x][0:6]

        x += 1
             
print(result)

# [['今天適合出門', '你,我,他他', '她'], ['一二三,四五', '六七,八,九', '十']]


   

0
hokou
iT邦新手 2 級 ‧ 2021-10-28 09:01:00

找資料意外的發現寫法還不少
可以參考 stackoverflow 上大家的寫法

Split string every nth character?
Split string into strings by length?

paragraph = [['今天適合出門','你,我,他他她'],['一二三,四五六七,八,九十']]

# 切割字數
n = 6

new = []

for a in paragraph:
    temp = []
    for b in a:
        c = [b[i:i+n] for i in range(0, len(b), n)]
        temp.extend(c)
    new.append(temp)

print(new)

# 用 re
import re

new = []

for a in paragraph:
    temp = []
    for x in a:
        c = [x for x in re.split(r'(.{%s})'%n, x) if x]
        temp.extend(c)
    new.append(temp)

print(new)
# [['今天適合出門', '你,我,他他', '她'], ['一二三,四五', '六七,八,九', '十']]

我要發表回答

立即登入回答