美文网首页
python的内建序列函数

python的内建序列函数

作者: 妈耶0000 | 来源:发表于2019-07-09 17:47 被阅读0次
1.enumerate
我们经常需要在遍历一个序列的同时追踪当前元素的索引。

>> some_list = ['foo','bar','baz']
>> for i,v in enumerate(some_list):
          print(i,v)
0 foo
1 bar
2 baz


mapping = {}
for i,v in enumerate(some_list):
    mapping[i] = v

print(mapping)
{0: 'foo', 1: 'bar', 2: 'baz'}


2. zip
1.zip是将列表、元祖或者其他序列的元素配对,
新建一个元祖构成的列表

>> seq1 = ['foo','bar','baz']
>> seq2 = ['one','two','three']

>> zipped = zip(seq1,seq2)
>> print(zipped)
 <zip at 0xad10c48>
>> list(zipped)
[ ('foo', 'one'), 
 ('bar', 'two'), 
 ('baz', 'three') ]



2.zip可以处理任意长度的序列
它生成列表长度由最短的序列决定

>> seq3 = [False,True]
>> list(zip(seq1,seq2,seq3))
[  ('foo', 'one', False), 
   ('bar', 'two', True)   ]



3.zip的常用场景为同时遍历多个序列
有时候会和enumerate同时使用
for i,(a,b) in enumerate(zip(seq1,seq2)):
      print('{0}:{1},{2}'.format(i,a,b))
0: foo,one
1: bar,two
2: baz,three



4.给定一个已配对的序列时,zip函数可以拆分
>> pit = [('a','x'),('b','y'),('c','z')]
>> first,last = zip(*pit)
>> first
('a', 'b', 'c')
>> last
('x', 'y', 'z')


3. reversed.是一个生成器,后续讨论,如果没有实例化(list或者for循环)的时候,它并不会产生一个倒序的序列
1.reversed函数将序列的元素倒序排序

>> reversed(range(10))
<range_iterator at 0xb09ee70>
>> for i in  reversed(range(10)):
       print(i)
9
8
7
6
5
4
3
2
1
0
>> list(reversed(range(10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


相关文章

  • python的零碎知识点

    zip()函数 它是Python的内建函数,(与序列有关的内建函数有:sorted()、reversed()、en...

  • Python初学笔记之过滤器(filter)

    Python内建的filter()函数用于过滤序列。和map()类似,filter()函数也接收一个函数和一个序列...

  • filter

    Python内建的filter()函数用于过滤序列。 和map()类似,filter()也接收一个函数和一个序列。...

  • Python filter()过滤函数

    Python内建的filter()函数用于过滤序列。 和map()类似,filter()也接收一个函数和一个序列。...

  • 【20-2】filter

    Python内建的filter()函数用于过滤序列。 和map()类似,filter()也接收一个函数和一个序列。...

  • filter

    Python内建的filter()函数用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和...

  • 2022-04-15 filter 和 sorted

    Python内建的filter()函数用于过滤序列 和map()类似,filter()也接收一个函数和一个序列。和...

  • filter

    filter: Python内建的filter()函数用于过滤序列。 filter()和map()类似 filte...

  • 【python】第四周filter

    filter Python内建的filter()函数用于过滤序列。map()类似,filter()也接收一个函数和...

  • python 高阶函数

    1. map/reduce函数 2. filter:Python内建的filter()函数用于过滤序列 3. so...

网友评论

      本文标题:python的内建序列函数

      本文链接:https://www.haomeiwen.com/subject/qtcfkctx.html