Python·next() function

describe

next() returns the next item of the iterator.

The next() function is used in conjunction with the iter() function that generates an iterator .

grammar

next syntax:

next(iterable[, default])

Parameter Description:

  • iterable -- the iterable object
  • default -- optional, used to set the default value to be returned when there is no next element, if not set and there is no next element, a StopIteration exception will be triggered.

return value

Return to the next item.

example

 

There is a csv package (build-in) in python, which has a reader that reads the data in the csv file by line

reader.next() function: print the header of the first line in the csv file

(usage in python3)

  1. allElectronicsData = open(r'C:/pydata/AllElectronics.csv', 'rt')
  2. reader = csv.reader(allElectronicsData)
  3. headers = next(reader)

(usage in python2)

  1. allElectronicsData = open(r'C:/pydata/AllElectronics.csv', 'rb')
  2. reader = csv.reader(allElectronicsData)
  3. headers = reader.next()

Guess you like

Origin blog.csdn.net/qq_37865996/article/details/124286268