python 实现list或string按指定分段

yipeiwu_com5年前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实现压缩文件夹与解压缩zip文件的方法

本文实例讲述了Python实现压缩文件夹与解压缩zip文件的方法。分享给大家供大家参考,具体如下: 直接上代码 #coding=utf-8 #甄码农python代码 #使用zipfi...

以windows service方式运行Python程序的方法

本文实例讲述了以windows service方式运行Python程序的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python # coding...

pandas 对每一列数据进行标准化的方法

两种方式 >>> import numpy as np >>> import pandas as pd Backend TkAgg is in...

python 协程中的迭代器,生成器原理及应用实例详解

python 协程中的迭代器,生成器原理及应用实例详解

本文实例讲述了python 协程中的迭代器,生成器原理及应用。分享给大家供大家参考,具体如下: 1.迭代器理解 迭代器: 迭代器是访问可迭代对象的工具 迭代器...

在Django框架中设置语言偏好的教程

一旦你准备好了翻译,如果希望在Django中使用,那么只需要激活这些翻译即可。 在这些功能背后,Django拥有一个灵活的模型来确定在安装和使用应用程序的过程中选择使用的语言。 要设定一...