python学习12——循环和列表

the_count = [1, 2, 3, 4,5]
for num in the_count:
 print("This is number %r" % the_count)

输出结果:

如果是要依次打印列表中的数字,则

the_count = [1, 2, 3, 4,5]
for num in the_count:
 print("This is number %d" % num)

此时输出结果为:

这里只做两处修改:

1、格式化字符%r 改为 %d

2、print 一行中the_count 改为 num

the_count = [1, 2, 3, 4,5]
fruits = ['apple', 'orange', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

for num in the_count:
 print("This is number %d" % num)
for fruit in fruits:
 print("This is %s." % fruit)
for i in change:
 print("I got %r." % i)
elements = []
for i in range (0,6):
 print("Adding %d to the list." % i)
 elements.append(i)
for i in elements:
 print("Element was: %d." % i)
 

输出结果:

其中append() 方法用于在列表末尾添加新的对象。extend()方法只接受一个列表作为参数,并将该参数的每个元素都添加到原有的列表中。

原文地址:https://www.cnblogs.com/shannon-V/p/9554893.html