1

## python list切分問提

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

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

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

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

``````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

``````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)
# [['今天適合出門', '你，我，他他', '她'], ['一二三，四五', '六七，八，九', '十']]
``````