在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 請問在python里 L=[a,b,c,d,e,...] 數(shù)組截取怎么按照每三個

請問在python里 L=[a,b,c,d,e,...] 數(shù)組截取怎么按照每三個元素截???

有一組數(shù)組:

L = [a, b, c, d, e, ...]

通過 python 的話,要怎么可以把這段數(shù)組重新分成每三個元素一個新的組合,就像:

[a, b, c], [d, e, f], [g, h, i] ....
回答
編輯回答
雨蝶

定義函數(shù):

def partition_by_n(lst, n):
    groups = []
    for idx in range(len(lst)):
        if idx%3 == 0:
            groups.append(lst[idx:idx+3])
    return groups

使用:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> partition_by_n(lst, 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

我回答過的問題: Python-QA

2017年5月21日 17:21
編輯回答
哚蕾咪
l = [1,2,3,4,5,6,7,8,9]

def split(list):
  
  #空list用于輸出
  new_l = []
  
  #走循環(huán)
  for i in range(len(l)):
    #把list的前三個值插入空list
    new_l.append(l[:3])
    #刪掉剛剛被插的那三個值
    del l[:3]
    #如果list空了,就停止循環(huán)
    if len(l) <= 0:
      break
  #把結果輸出
  return new_l
  
a = split(l)

print(a)

>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2017年5月3日 05:51
編輯回答
有你在
L = [a, b, c, d, e, ...]
[L[i:i+3] for i in range(0,len(L),3)]
2017年9月13日 05:34