习题38 列表的操作
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
# 将ten_things中的内容按空格分隔开
stuff = ten_things.split(' ')
# 定义变量
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
# 创建while循环,该循环在stuff变量的长度为10时停止。
while len(stuff) != 10:
# 将more_stuff列表中的最后一个元素删除,并将该值赋给next_one
next_one = more_stuff.pop()
print("Adding:", next_one)
# 将next_one的值添加在stuff列表的最后
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.")
# 输出stuff列表索引值为1的元素(第二个元素)
print(stuff[1])
# 输出stuff列表的最后一个元素
print(stuff[-1]) # whoa! fancy!
# 将stuff列表的最后一个元素删除,并输出该值
print(stuff.pop())
# 将stuff中的元素以空格连接,并生成新的字符串
print(' '.join(stuff)) # what? cool!
# 将stuff列表中的索引3,4位置的元素以#连接,并生成新的字符串
print('#'.join(stuff[3:5])) # super stellar!
Wait there are not 10 things in that list. Let's fix that.
Adding: Boy
There are 7 items now.
Adding: Girl
There are 8 items now.
Adding: Banana
There are 9 items now.
Adding: Corn
There are 10 items 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
- 用for循环重写while循环
for len_stuff in stuff:
if len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding:", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
列表的特性
- 有序的列表:是的,纸牌是从头到尾有序排列的。
- 要存储的东西:就是我的纸牌了
- 随机访问:我可以从牌中抽取任意一张。
- 线性:如果我要找到某张牌,我可以从第一张开始,依次寻找。
- 通过索引:差不多是这样,如果我告诉你找出第19张牌,你需要数到19然后找到这张牌。在 Python列表里,如果你要某个索引位置的牌,计算机可以直接跳到索引对应的位置将其找出来
你只能使用数值来获得列表中的项
.join()方法
描述
.join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
语法
str.join(sequence)
参数
sequence – 要连接的元素序列。
返回值
返回通过指定字符连接序列中元素后生成的新字符串。
实例
str = "-";
seq = ("a", "b", "c") # 字符串序列
print str.join( seq )
a-b-c