python38使用_笨方法学Python 习题38:列表的操作

列表的操作:

这里先复习一下之前遇见过的函数:split()通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个子字符

str.split(str="", num=string.count(str))len() 返回列表元素个数

join() 用于将序列中的元素以指定的字符连接生成一个新的字符串。

str.join(sequence)pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

list.pop([index=-1])

本节的代码:

ten_things = "Apples Oranges Crows Telephone Light Sugar" # 将字符串赋值给变量 ten_things

print("Wait there are not 10 things in that list.Let's fix that.") # 打印字符串

stuff = ten_things.split(' ') # 通过指定分隔符对字符串进行分割并返回一个列表,然后赋值给变量stuff

# 定义列表more_stuff

more_stuff = ["Day", "Night", "Song", "Frisbee",

"Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10: #调用函数len(),参数为stuff,判断布尔表达式len(stuff) != 10的真假,若为True,则一直执行以下代码

next_one = more_stuff.pop() # 调用pop()函数将列表more_stuff指定位置的元素移除,同时将移除的元素赋值给变量next_one,不填写位置参数则默认删除最后一位

print("Adding: ", next_one) # 打印字符串和变量next_one

stuff.append(next_one) # 使用 append() 函数在 stuff 列表的尾部追加元素 next_one

print(f"There are {len(stuff)} item now.") # 打印字符串

print("There we go: ",stuff) #打印字符串和变量stuff

print("Let's do some things with stuff.") #打印字符串

print(stuff[1]) # 打印列表stuff第二个的元素

print(stuff[-1]) # whoa! fancy #打印列表stuff最后一个元素

print(stuff.pop()) # 调用pop()函数将列表stuff最后一个元素移除并打印出来

print(' '.join(stuff)) # what? cool! # 调用join函数,参数为stuff,将列表stuff中的元素以' '连接生成一个新的字符串,然后打印该字符串

print('#'.join(stuff[3:5])) # super steller! # 调用join函数,参数为stuff[3:5],将列表stuff中第四和第五个元素以'#'连接生成一个新的字符串,然后打印该字符串

运行结果:

> python .\ex38.py

Wait there are not 10 things in that list.Let's fix that.

Adding: Boy

There are 7 item now.

Adding: Girl

There are 8 item now.

Adding: Banana

There are 9 item now.

Adding: Corn

There are 10 item now.

There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']

Let's do some things with stuff.

Oranges

Corn

Corn

Apples Oranges Crows Telephone Light Sugar Boy Girl Banana

Telephone#Light

加分习题:

Q1.取出每一个被调用的函数,跟着将函数调用的步骤翻译成Python实际执行的动作。例如,more_stuff.pop()其实是pop(more_stuff)。

stuff = ten_things.split(' ')实际执行为 stuff = split(ten_things, ' ')

next_one = more_stuff.pop()实际执行为 next_one = pop(more_stuff)

stuff.append(next_one)实际执行为 append(stuff,next_one)

stuff.pop()实际执行为 pop(stuff)

Q2.将两种方式翻译为自然语言。例如,more_stuff.pop()可以翻译成"在more_stuff上调用pop函数",而pop(more_stuff)的意思是"用more_stuff作为参数调用pop函数"。弄懂为什么这其实是同一件事情。

Q3.上网阅读一些关于“面向对象编程(Object Oriented Programming)”的资料。晕了吧?嗯,我以前也是。别担心。你将从这本书学到足够用的关于面向对象编程的基础知识,而以后你还可以慢慢学到更多。

Q4.查一下 Python中的 “class” 是什么东西。不要阅读关于其他语言的 “class” 的用法,这会让你更糊涂。

Q5.如果你不知道我讲的是什么,别担心。程序员为了显得自己聪明,发明了面向对象编程,然后他们就开始滥用这个东西了。如果你觉得这东西太难,可以试试用"函数编程(functional programming)"。

Q6.在实际生活中找出10个适合用列表表达的例子。写一些脚本,用来处理这些数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值