l = [1 2 3 4 5 6 7 8 9 10]
和组大小grp和步骤
grp = 3; step = 2
我想返回一份清单.注意最后的重复
1 2 33 4 55 6 77 8 99 10 1
或者如果
grp= 4; step = 2
输出应该是
1 2 3 43 4 5 65 6 7 87 8 9 10
这是我提出的代码,它没有做循环的事情.
但是想知道是否有更小或更简单的解决方案
def groupList(l,grp,step): opList = List() for x in range(0,len(l)): if (x+grp<len(l)): opList.append(str(l[x:x+grp])) return opList解决方法 您可以利用xrange或range中的step函数,具体取决于您使用的python版本.然后像这样以列表的长度回绕mod
import sysdef groupList(l,step): newList=[] d = len(l) for i in xrange(0,len(l),step): for j in xrange(grp): newList.append(l[(i+j)%d]) sys.stdout.write(str(l[(i+j)%d]) + ' ') printl = [1,2,3,4,5,6,7,8,9,10]print groupList(l,2)1 2 3 3 4 5 5 6 7 7 8 9 9 10 1 [1,10,1]print groupList(l,2)1 2 3 4 3 4 5 6 5 6 7 8 7 8 9 10 9 10 1 2[1,1,2]总结
以上是内存溢出为你收集整理的使用步长python列出一个列表项?全部内容,希望文章能够帮你解决使用步长python列出一个列表项?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)