比如:将list:[1,2,3,4,5,6,7,8,9]
按照下标顺序分成3组:[1,2,3] [4,5,6] [7,8,9]
或分成5组:[1,2,] [3, 4] [5,6] [7, 8] [ 9 ]
解决办法:
a=[1,2,3,4,5,6,7,8,9]
for i in range(0,len(a),3):
b=a[i:i+3]
print(b)
a=[1,2,3,4,5,6,7,8,9]
for i in range(0,len(a),2):
b=a[i:i+2]
print(b)
<pre style="transition-duration: 0.2s; transition-property: background-color, border-color, border-radius, padding, margin, color, opacity; overflow: auto; margin: 0px 0px 0px 22px; font-size: 12px; font-family: "Courier New"; overflow-wrap: break-word;">a=[1,2,3,4,5,6,7,8,9,10] for i in range(0,len(a),3):
b=a[i:i+3] print b</pre>
如果有10个数:
<pre style="transition-duration: 0.2s; transition-property: background-color, border-color, border-radius, padding, margin, color, opacity; overflow: auto; margin: 0px 0px 0px 22px; font-size: 12px; font-family: "Courier New"; overflow-wrap: break-word;">
# 设置函数
# listTemp 为列表 平分后每份列表的的个数n
def func(listTemp, n):
for i in range(0, len(listTemp), n):
yield listTemp[i:i + n]