Python built-in functions reversed, enumerate (continuously updated)

1、reversed

2、enumerate

(1) enumerate() description

  • Enumerate means enumeration and enumeration in the dictionary
  • For an iterable/traversable object (such as a list, a string), enumerate will form an index sequence, which can be used to get the index and value at the same time
  • enumerate is mostly used to get counts in for loops
  • For example, for a seq, we get:

    (0, seq[0]), (1, seq[1]), (2, seq[2])
    • 1
  • enumerate() returns an enumerate object, for example: 
    write picture description here

(2) use of enumerate

  • If you want to traverse both the index and the elements of a list, you can first write this:
list1 = ["这", "是", "一个", "测试"]
for i in range (len(list1)):
    print i ,list1[i]
  • 1
  • 2
  • 3
  • The above method is a bit cumbersome, using enumerate() will be more direct and elegant:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
    print index, item
>>>
012 一个
3 测试
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • enumerate can also receive a second parameter, which is used to specify the starting value of the index, such as:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
    print index, item
>>>
123 一个
4 测试
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(3) Supplement

If you want to count the number of lines in a file, you can write:

count = len(open(filepath, 'r').readlines())
  • 1

This method is simple, but can be slow and doesn't even work when the file size is large .

You can use enumerate():

count = 0
for index, line in enumerate(open(filepath,'r')): 
    count += 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325844579&siteId=291194637