Python中有一些内置函数很难归类但却非常好用和常用.我们这篇文章就来学习一下.
range
通过range(),你可以迅速地输出一串数字.你可以向range()传递三个参数,分别是开始的数字,结束的数字和步长(默认为1).
range(0,11)
输出结果为:range(0,11)
请注意输出结果range(0,11)还不是数字列表.因为range()只是生成器函数.生成器只是能生成信息而且不存储.如果要得到数字列表还需要加一个list().
#注意不包括11,就像切片不包含最后一个数字一样
list(range(0,11))
输出结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#2是步长,表示第2个数字和第一个数字跳跃了多长
list(range(0,11,2))
输出结果:
[0, 2, 4, 6, 8, 10]
list(range(0,101,10))
输出结果:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
enumerate
和for循环结合起来用,enumerate是一个非常强大的函数.让我们看一下下面的例子
index_count = 0
for letter in 'abcde':
print('At index{} the letter is {}'.format(index_count,letter))
输出结果为:
At index0 the letter is a
At index0 the letter is b
At index0 the letter is c
At index0 the letter is d
At index0 the letter is e
编程中记录循环次数是经常发生的.使用enumerate函数,你就不用再担心什么时候创建循环,什么时候更新index_count和循环变量的值得问题.
#请注意元组解包
for i , letter in enumerate('abced'):
print('At index{} the letter is {}'.format(index_count,letter))
输出结果为:
At index0 the letter is a
At index0 the letter is b
At index0 the letter is c
At index0 the letter is e
At index0 the letter is d
zip
注意一下enumerate返回的格式是什么?我们使用list()来看结果.
list(enumerate('abcde'))
输出结果是:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
原来输出结果是以元组为元素的列表,这意味着我们可以在循环中利用元组解包.这种数据结构在python非常常见,特别是在使用外部库时.你可以使用zip()快速封装另个列表放到元组里,再用这些元组组成一个新的列表.
my_list1 = [1,2,3,4,5]
my_list2 = ['a', 'b', 'c', 'd', 'e']
zip(my_list1,my_list2)
list(zip(my_list1,my_list2))
输出结果是:
<zip at 0x1fed96f4108>
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
进一步,我们可以把zip()和循环结合起来.
for item1, item2 in zip(my_list1,my_list2):
print('for this tuple, the first item is {} and second item is {}'.format(item1,item2))
输出结果是:
for this tuple, the first item is 1 and second item is a
for this tuple, the first item is 2 and second item is b
for this tuple, the first item is 3 and second item is c
for this tuple, the first item is 4 and second item is d
for this tuple, the first item is 5 and second item is e
in
我们可以用in迅速查看列表是否含有某一个元素
'x'in ['x', 'y', 'z']
'x' in ['1','2','3']
输出结果为:
True
False
min和max
使用min()和max()迅速查看列表里的最小值和最大值
mylist = [10,20,30,40,100]
min(mylist)
max(mylist)
输出结果为:
10
100
random
random是python内置的库.random库里含有很多很好用的函数.这里给大家介绍两个很好用的函数.
from random import shuffle
mylist = [10,20,30,40,100]
shuffle(mylist)#像洗牌一样随机打乱列表的元素
mylist
输出结果:
[20, 40, 30, 100, 10] (注意:可能是其他的顺序)
from random import randint
randint(0,100)
输出结果:(随机返回0-100的整数,含0和100)
input
input('enter something into this box: ')
输出结果:
enter something into this box: (用户自己输入)
比如enter something into this box:很棒
则返回很棒