Python提供4种内置数据结构,分别是列表、元组、字典和集合。这些数据结构可在代码中直接使用, 无需导入
列表类似其它语言中的数组,列表中的元素从0开始编号。列表是可变的,可以通过增加和修改元素来 改变列表。
列表用中括号包围,对象之间用逗号分隔
list = [1, 2, 3, 4]
price = []
temps = [32.0, 212.0]
words = ['hello', 'world']
list = ['Hello', 2.2]
mix = [[1, 2, 3], ['a', 'b', 'c'] ]
vowels = ['a', 'e', 'i', 'o', 'u']
word = 'Milliways'
for letter in word:
if letter in vowels:
print(letter)
>>> found = []
>>> len(found)
0
>>> found.append('a')
>>> len(found)
1
if 'u' not in found:
found.append('u')
>>> nums = [1, 2, 3, 4]
>>> nums.remove(3)
>>> nums
[1, 2, 4]
pop方法根据对象的索引值从列表上删除和返回一个对象,如果没有指定索引值,删除并返回最后一个对象。
>>> nums = [1, 2, 3, 4]
>>> nums.remove(3)
>>>
>>> nums
[1, 2, 4]
>>> nums.pop()
4
>>> nums
[1, 2]
>>> nums.pop(0)
1
>>> nums
[2]
>>>
extend方法将第二个列表元素合并到第一个列表
>>> nums.extend([3,4])
>>> nums
[2, 3, 4]
>>>
insert方法将对象插入到指定索引值前面
>>> nums.insert(0, 1)
>>> nums
[1, 2, 3, 4]
copy方法完成列表的复制
first = second.copy()
>>> nums[0:10:3] //每3个字母选择1个字母,直到索引位置为10
[1, 4, 7]
>>> nums[3:]//跳过3个字母,给出其余的字母
[4, 5, 6, 7]
>>> nums[:10]//索引位置10前的所有字母
[1, 2, 3, 4, 5, 6, 7]
>>> nums[::2] //每2个字母选择1个
[1, 3, 5, 7]
>>> book = "the book"
>>> booklist = list(book)
>>> book
'the book'
>>> ''.join(booklist[0:3])
'the'
欢迎访问个人小站Introduction · 小蜗牛的site
页面更新:2024-05-18
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号