range使用方法

使用python的人都知道range()函数非常方便,今天再用到他的时候发现了非常多曾经看到过可是忘记的细节。

这里记录一下:

range(1,5)#代表从1到5(不包括5)
[1,2,3,4]
range(1,5,2)#代表从1到5,间隔2(不包括5)
[1,3]
range(5)#代表从0到5(不包括5)
[0,1,2,3,4]

再看看list的操作:

array= [1,2,5,3,6,8,4]
#事实上这里的顺序标识是
[1,2,5,3,6,8,4]
(0123456)
(-7,-6,-5,-4,-3,-2,-1)
 
array[0:]#列出0以后的
[1,2,5,3,6,8,4]
array[1:]#列出1以后的
[2,5,3,6,8,4]
array[:-1]#列出-1之前的
[1,2,5,3,6,8]
array[3:-3]#列出3到-3之间的
[3]

for
loop

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number # same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit # also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i # we can also build lists, first start with an empty one
elements = [] # then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i) # now we can print them out too
for i in elements:
print "Element was: %d" % i

输出

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'dimes'
I got 3
I got 'quarters'
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

最新文章

  1. yii2 rbac-plus的使用
  2. 前后台数据传输两种方式:servlet、Controller
  3. activiti自定义流程之自定义表单(二):创建表单
  4. node系列4
  5. zabbix 添加自定义key
  6. 「技巧」如何将Sketch改为深色模式
  7. CF #552(div3)F 背包问题
  8. 扩展的GM命令
  9. Vue项目在真机测试
  10. 在vue配置sass
  11. 2017.7.12 Python的6种内建序列及操作
  12. es6(13)--Promise
  13. webpack原理与实战
  14. [Go] Returning Multiple Values from a Function in Go
  15. Android开发中无处不在的设计模式——动态代理模式
  16. Java——IO类,字符缓冲区
  17. Spring源码分析(十八)创建bean
  18. how to show video in website
  19. Spring工具类ToStringBuilder用法简介
  20. 关于reduce的使用方法

热门文章

  1. Postgres 将查询结果同时插入数据表
  2. CentOS7安装Code::Blocks
  3. sqlserver中top 1 赋值的问题
  4. 用jquery动态生成的元素绑定事件
  5. 【bzoj4448】[Scoi2015]情报传递 主席树
  6. LoadRunner中请求HTTPS页面。
  7. mysql 排序字段与索引有关系吗?
  8. 洛谷 [P1552] 派遣
  9. 博客移至CSDN
  10. UVA1218 Perfect Service