Py学习  »  mkrieger1 John Antonio Anselmo  »  全部回复
回复总数  1
3 年前
回复了 mkrieger1 John Antonio Anselmo 创建的主题 » 如何在python中按n个元素分组元素,而无需列表切片?

使用模数运算符 % .

def split_by_n(n, lst):
  final = []
  sublist = []
  for i in range(0, len(lst)):
    if i % n != 0: # if i/n has no remainders
      sublist.append(lst[i])
    elif i != 0: # Reached the end of a sublist. Append to parent and reset.
      final.append(sublist)
      sublist = []
      sublist.append(lst[i])
    else: # 0 mod n is 0, so just make sure to add it anyways
      sublist.append(lst[i])
  final.append(sublist)
  return final