社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

mkrieger1 John Antonio Anselmo

mkrieger1 John Antonio Anselmo 最近创建的主题
mkrieger1 John Antonio Anselmo 最近回复了
2 年前
回复了 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