python怎么调换一组数的顺序

[复制链接]
查看11 | 回复3 | 2013-10-20 14:09:50 | 显示全部楼层 |阅读模式
$ pythonPython 2.7.3 (default, Jan2 2013, 16:53:07) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> D=[1,2,3,4,5,'a','b','c']>>> index=5>>> def shift(lst, idx):...
return lst[idx+1:]+[lst[idx],]+lst[:idx]... >>> shift(D,index)['b', 'c', 'a', 1, 2, 3, 4, 5]>>>...
回复

使用道具 举报

千问 | 2013-10-20 14:09:50 | 显示全部楼层
应该是D[index+1:] + [D[index]] + D[:index]这个报错主要是D[index]引起的,D[index]访问的是列表里的a,是int类型,而D[index+1:]是一个列表,列表只可以和一个迭代器相加,而int类型不可迭代,因此抛出异常...
回复

使用道具 举报

千问 | 2013-10-20 14:09:50 | 显示全部楼层
这个报错主要是D[index]引起的,D[index]访问的是列表里的a,是int类型,而D[index+1:]是一个列表,列表只可以和一个迭代器相加,而int类型不可迭代,因此抛出异常,解决办法如下:D=[1,2,3,4,5,'a','b','c']index=5def shift(lst, idx):
return lst[idx+1:]+[...
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行