《笨方法学 Python 3》38.列表的操作

我们已经学过了列表,并且对列表进行过“追加”(append)操作,下面看看列表的工作原理:

当你看到mystuff.append('hello')这样的代码时,事实上已经在python内部激发了一个连锁反应,导致mystuff列表发生了一些变化:

1. Python 看到你用到了mystuff,于是就去查找这个变量。

2. 一旦找到了mystuff,就轮到处理句点(.)这个运算符,而且开始查看mystuff内部的一些变量了。由于mystuff 是一个列表,Python 知道mystuff支持一些函数。

3. 接下在再处理append。Python会将append 和mystuff 支持的所有函数的名称一一对比,如果确实有一个叫append的函数,那么Python就会使用这个函数。

3. 接下来Python看到了括号( ( )并意识到:“噢,原来这应该是个函数。”到了这里,Python就会正常调用这个函数了,不过这个函数还要带一个额外的参数才行。

4. 这个额外的参数实际就是mystuff,是不是很奇怪?不过这就是Python的工作原理,真正发生的事情其实是append(mystuff,‘hello’),不过你看到的只是 mystuff.append('hello')。


基础练习:

ten_things = "Apples Oranges Crows Telephone Light Sugar"

print("What there are not 10 things in that list.Let's fix that.")

stuff = ten_things.split(' ')
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']

while len(stuff) != 10:
	next_one = more_stuff.pop()
	print("Adding: ", next_one)
	stuff.append(next_one)
	print(f"There are {len(stuff)} items now.")

print("There we go: ", stuff)

print("Let's do some things with stuff")

print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5]))

结果:


 看起来比较陌生,实际前面都有讲过的东西:

1. split():分割函数;

2. pop():截取list中的参数并返回该参数,默认截取list中的最后一个,pop(1):截取第2个参数;

3.  ’#‘.join():将列表、元祖、字典中的元素以指定的字符(例如#)连接生成一个新的字符串;                                                                               例如:'---'.join(stuff),以“---”符号将 stuff 中的字符串连接起来,并且只能链接字符串str,数值不行;                                             stuff = ['L', 'o', 'v', 'e']                                                                                                                                                                           print('---'.join(stuff))      输入结果:>>>L---o---v---e

END!!!

猜你喜欢

转载自blog.csdn.net/waitan2018/article/details/82961081
今日推荐