内建序列函数

作者: 庵下桃花仙 | 来源:发表于2018-12-24 22:56 被阅读1次

1、 enumerate

目的:遍历一个序列同时跟踪当前元素索引。

Python中内建函数enumerate,返回(i, value)元组序列,其中i是元素的索引,value是元素的值。

In [4]: some_list = ['foo', 'bar', 'baz']

In [5]: mapping = {}

In [6]:  for i,v in enumerate(some_list):
   ...:      mapping[v] = i
   ...:

In [7]: mapping
Out[7]: {'foo': 0, 'bar': 1, 'baz': 2}

2、sorted

sorted 函数返回一个根据任意序列中元素新建的已排序的列表。

In [8]: sorted([7, 1, 2, 6, 0, 3, 2])
Out[8]: [0, 1, 2, 2, 3, 6, 7]

In [9]: sorted('horse race')
Out[9]: [' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's']

3、zip

zip 将列表、元组或其它序列的元素配对,新建一个元组构成的列表。

In [10]: seq1 = ['foo', 'bar', 'baz']

In [11]: seq2 = ['one', 'two', 'three']

In [12]: zipped = zip(seq1, seq2)

In [13]: list(zipped)
Out[13]: [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]

In [14]: seq3 = [False, True]

In [15]: list(zip(seq1, seq2, seq3))
Out[15]: [('foo', 'one', False), ('bar', 'two', True)]

zip 常用场景为同时遍历多个序列,会和 enumerate 同时使用。

In [17]: 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

给定一个配对的序列,zip 函数可将其拆分。

In [18]: pitchers = [('Nolan', 'Ruan'), ('Roger', 'Clemens'),
    ...: ('Schilling', 'Curt')]

In [19]: first_names, last_names = zip(*pitchers)

In [20]: first_names
Out[20]: ('Nolan', 'Roger', 'Schilling')

In [21]: last_names
Out[21]: ('Ruan', 'Clemens', 'Curt')

4、reversed

reversed 函数将序列的元素倒序排列。

In [22]: list(reversed(range(10)))
Out[22]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

相关文章

  • python的零碎知识点

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

  • 内建序列函数

    1、 enumerate 目的:遍历一个序列同时跟踪当前元素索引。 Python中内建函数enumerate,返...

  • 内建函数

    内建函数filter(),map(),apply(),reduce() filter(函数,序列):按照条件过滤指...

  • 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()也接收一个函数和一个序列。和...

  • Python中的可变类型与不可变类型

    1.列表操作 2.序列类型可用的内建函数 3.序列操作符 4.列表类型内建函数 5.列表解析 列表解析的一般语法:...

网友评论

    本文标题:内建序列函数

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