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设计模式之访问者模式

轻松掌握python设计模式之访问者模式

本文实例为大家分享了python访问者模式代码,供大家参考,具体内容如下 """访问者模式""" class Node(object): pass class A(Node):...

Python3中的列表,元组,字典,字符串相关知识小结

一、知识概要   1. 列表,元组,字典,字符串的创建方式   2. 列表,元组,字典,字符串的方法调用   3. 列表,元组,字典,字符串的常规用法 二、列表 # 列 表 # 列...

举例讲解Python中装饰器的用法

由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。 >>> def now(): ... print '2013-12-25'...

Python实现的各种常见分布算法示例

Python实现的各种常见分布算法示例

本文实例讲述了Python实现的各种常见分布算法。分享给大家供大家参考,具体如下: #-*- encoding:utf-8 -*- import numpy as np from s...

对PyTorch torch.stack的实例讲解

不是concat的意思 import torch a = torch.ones([1,2]) b = torch.ones([1,2]) torch.stack([a,b],1) (...