python

python循环打印的技巧有哪些

小樊
86
2024-08-10 02:43:37
栏目: 编程语言
Python开发者服务器,限时0元免费领! 查看>>

  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]

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:python循环打印的循环控制技巧有哪些

0
看了该问题的人还看了