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设计】。

相关文章

python super用法及原理详解

这篇文章主要介绍了python super用法及原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 概念 super作为pyth...

Python 遍历列表里面序号和值的方法(三种)

Python 遍历列表里面序号和值的方法(三种)

三种遍历列表里面序号和值的方法: 最近学习python这门语言,感觉到其对自己的工作效率有很大的提升,特在情人节这一天写下了这篇博客,下面废话不多说,直接贴代码 #!/usr/bin...

Python实现账号密码输错三次即锁定功能简单示例

本文实例讲述了Python实现账号密码输错三次即锁定功能。分享给大家供大家参考,具体如下: 初学Python—1 #实现账号输错三次即锁定 user = "hubery" passw...

Python读写文件模式和文件对象方法实例详解

Python读写文件模式和文件对象方法实例详解

本文实例讲述了Python读写文件模式和文件对象方法。分享给大家供大家参考,具体如下: 一. 读写文件模式 利用open() 读写文件时,将会返回一个 file 对象,其基本语法格式如...

讲解Python中fileno()方法的使用

 fileno()方法返回所使用的底层实现,要求从操作系统I/O操作的整数文件描述符。 语法 以下是fileno()方法的语法: fileObject.fileno();...