Python笔记-列表

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
in检查成员关系
if 'u' not in found:
    found.append('u')
从列表中删除对象
>>> nums = [1, 2, 3, 4]
>>> nums.remove(3)
>>> nums
[1, 2, 4]

删除列表所有元素

c_list = [20, 'crazyit', 30, -4, 'crazyit', 3.4]
c_list.clear()
print(c_list)

[]
从列表弹出对象

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'

results matching ""

    No results matching ""