python 实现list或string按指定分段

yipeiwu_com6年前Python基础

我就废话不多说了,直接上代码吧!

#方法一
def list_cut(mylist,count):
  length=len(mylist)
  merchant=length//count
  re_merchant=merchant+1*(0 if length%count==0 else 1)
  begin=0
  result_list = []
  while (count>0):
    result_list.append(mylist[begin:begin+re_merchant])
    begin=begin+re_merchant
    count=count-1
  return result_list
mylist=[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8]
hello=list_cut(mylist,5)
 
#方法二
def list_cut2(mylist,count):
  length = len(mylist)
  merchant = length // count
  re_merchant = merchant + 1 * (0 if length % count == 0 else 1)
  print(re_merchant)
  return [mylist[i:i+re_merchant] for i in range(0,length,re_merchant)]
hello2=list_cut2(mylist,6)

以上这篇python 实现list或string按指定分段就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3 利用requests 库进行post携带账号密码请求数据的方法

如下所示: import urllib,json,requests url = 'http://127.0.0.1:8000/account/login' headers = {}...

Python构建XML树结构的方法示例

本文实例讲述了Python构建XML树结构的方法。分享给大家供大家参考,具体如下: 1.构建XML元素 #encoding=utf-8 from xml.etree import E...

用python实现的可以拷贝或剪切一个文件列表中的所有文件

复制代码 代码如下:# coding:utf-8 import os import sys def cut_and_paste_file(source, destination): &n...

ubuntu系统下使用pm2设置nodejs开机自启动的方法

1.安装pm2 : npm install pm2 -gd 这时在命令行下执行pm2命令可能找不到,需要执行如下命令 1.创建软链接:ln -s /home/XXX/node-node-...

python获取Linux发行版名称

我必须从Python脚本中获取Linux发行版名称。dist平台模块中有一个方法: import platform platform.dist() 但在我的Arch Linux下...