温馨提示×

python循环打印的技巧有哪些

小樊
83
2024-08-10 02:43:37
栏目: 编程语言

  1. 使用for循环打印列表中的元素:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
  1. 使用while循环打印一定次数的内容:
count = 0
while count < 5:
    print("Hello")
    count += 1
  1. 使用range()函数生成指定范围的数值进行循环打印:
for i in range(5):
    print(i)
  1. 结合enumerate()函数获取列表中元素的索引进行循环打印:
fruits = ['apple', 'banana', 'cherry']
for idx, fruit in enumerate(fruits):
    print(idx, fruit)
  1. 使用zip()函数同时循环多个列表中的元素:
fruits = ['apple', 'banana', 'cherry']
prices = [1.2, 3.4, 5.6]
for fruit, price in zip(fruits, prices):
    print(fruit, price)
  1. 使用列表解析进行简洁的循环打印:
fruits = ['apple', 'banana', 'cherry']
[print(fruit) for fruit in fruits]

0