Python Everyday Series 1

Python Everyday

1. Three ways of looping with multiple lists in python

  • use range to generate a list of index
  • use enumerate to get a index for free
  • use zip to loop multiple list at the same time.
names = ['Alice', 'Bob', 'Chris']
ages = [22, 34, 32]

# use range to generate a list of index
for i in range(len(names)):
    print('name: {}, age: {} '.format(names[i],ages[i]))

# use enumerate to get a index for free
for i, name in enumerate(names):
     print('name: {}, age: {} '.format(name,ages[i]))

# use zip to loop multiple list at the same time.
for name, age in zip(names, ages):
     print('name: {}, age: {} '.format(name, age))

你可能感兴趣的:(Python)