Python列表-有序的可变对象集合

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]

从列表弹出对象

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

标签:对象   列表   数据结构   括号   逗号   字母   索引   元素   位置   方法

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top