《笨方法学 Python 3》32. for 循环和列表

        我们在开始使用 for 循环前,你需要在某个位置存放循环的结果。最好的方法就是使用列表(list),顾名思义,它就是一个从头到尾按顺序存放东西的容器。

        首先我们看看如何创建列表:

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

        就是以" [ "开头,以“ ] ”结尾,中间是你要放入列表的东西,用“ , ”隔开。这就是列表(list),然后Python接受这个列表以及里面所有的内容,将其赋值给一个变量。

基础练习:

        现在我们讲使用 for 循环创建一些列表,然后将它们打印出来:

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

# this first kind of for-loop goes through a list.///第一种for循环会通过一个列表
for number in the_count:
	print(f"This is count {number}")

#same as above.///同上
for fruit in fruits:
	print(f"A fruit of type: {fruit}")

#also we can go through mixed lists too.///我们也可以通过混合列表
#notice we have to use {} since we don't know what's in items.///注意,我们必须使用{}因为我们不知道里面是什么东西
for i in change:
	print(f"I got {i}")

#we can also build lists, first start with an empty one.///我们也可以建立列表,首先从一个空的开始
elements = []

#then use the range function to do 0 to 5 counts.///然后使用range函数来做0到5计数
for i in range(0,6):
	print(f"Adding {i} to the list.")
	#append is a function that lists understand.///append是一个列表理解的函数
	elements.append(i)
	
# now we can print them out too.///现在我们也可以把它们打印出来
for i in elements:
	print(f"Element was: {i}")

结果:


知识点:

1.  range() 函数:

  • range() 函数可以创建一个整数列表,一般用在 for 循环中。
  • 语法:range(start,stop,step) 
  • start:start 是计数开始,一般默认为0,例如 range(5)的意思就是 range(0, 5);
  • stop:stop 是计数结束,但不包含 stop,例如 range(0,5)是[0, 1, 2, 3, 4],不包含[5];
  • step:step 是步长(就是两数之间间隔),一般默认为1,例如 range(0,5)的意思就是 range(0, 5, 1);

实例: range(25) = range(0, 25)  :[0, 1, 2, 3, ...25]

            range(0,25,5)  :[0, 5, 10, 15, 20, 25]

2.  append()函数:

  • append() 函数可以在列表的尾部追加参数,例如:

  • append()  1次只能追加1个参数 ,它可以追加任何类型的参数
  • 还有一个expend() 函数也可以在列表后追加参数,但是它追假的参数类型必须是list,也就是在原来的list的尾部追加list。

        

END!!!

猜你喜欢

转载自blog.csdn.net/waitan2018/article/details/82824673