Python基础(二)之数据类型和运算(4)—— 列表

列表

Python 有几个 复合数据类型,用于表示其它的值。最通用的是 list (列表) ,它可以写作中括号之间的一列逗号分隔的值。列表的元素不必是同一类型:

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

索引:

names = [‘Alex‘,"Tenglan",‘Eric‘]
>>> names[0]
‘Alex‘
>>> names[2]
‘Eric‘
>>> names[-1]
‘Eric‘
>>> names[-2] #还可以倒着取
‘Tenglan‘

切片:

print(name_list[1:4])#取下标1至下标4之间的值,包括1,不包括4
print(name_list[1:-1])#取下标1至下标-1的值,不包括-1(-1为最右边的值)
print(name_list[1:])#从1开始取直到最后一个,不能写-1,只能这么写
print(name_list[1:len(name_list)])#同上

print(name_list[0:3])#从头开始取,取3个值
print(name_list[:3])#如果是从头开始取,0可以忽略,跟上句效果一样

print(name_list[0::2])#后面的2表示每隔一个元素,取一个
print(name_list[::2])#效果同上

print(name_list[-3:-1])#从右边数第3个到最后一个,不包括最后第一个print(name_list[-3:])#从右边数第3个到最后一个

所有的切片操作都会返回一个包含请求的元素的新列表。这意味着下面的切片操作返回列表一个新的(浅)拷贝副本:

print(name_list[:])

修改:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘强行从Eric前面插入‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
>>> names[2] = "该换人了"
>>> names
[‘Alex‘, ‘Tenglan‘, ‘该换人了‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]

也可以对切片赋值,此操作可以改变列表的尺寸,或清空它:

>>> letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]
>>> letters
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]
>>> # replace some values
>>> letters[2:5] = [‘C‘, ‘D‘, ‘E‘]
>>> letters
[‘a‘, ‘b‘, ‘C‘, ‘D‘, ‘E‘, ‘f‘, ‘g‘]
>>> # now remove them
>>> letters[2:5] = []
>>> letters
[‘a‘, ‘b‘, ‘f‘, ‘g‘]
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

追加:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘]
>>> names.append("我是新来的")
>>> names
[‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]

扩展:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘]
>>> b = [1,2,3]
>>> names.extend(b)
>>> names
[‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]

列表也支持连接这样的操作:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

插入:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
>>> names.insert(2,"强行从Eric前面插入")
>>> names
[‘Alex‘, ‘Tenglan‘, ‘强行从Eric前面插入‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]

>>> names.insert(5,"从eric后面插入试试新姿势")
>>> names
[‘Alex‘, ‘Tenglan‘, ‘强行从Eric前面插入‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]

删除:

>>> del names[2]
>>> names
[‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
>>> del names[4]
>>> names
[‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
>>>
>>> names.remove("Eric") #删除指定元素,只能删一个
>>> names
[‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
>>> names.pop() #删除列表最后一个值
‘我是新来的‘
>>> names
[‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘]

拷贝:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]

>>> name_copy = names.copy()
>>> name_copy
[‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]

此处的copy只能浅拷贝,即只能拷贝一层,例如:

>>> text = [‘a‘,‘b‘,‘c‘,‘d‘,[‘A‘,‘B‘,‘C‘],‘e‘,‘f‘]>>> text_copy = text.copy()
>>> text_copy
[‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘B‘, ‘C‘], ‘e‘, ‘f‘]
>>> text[4][1] = ‘ZZZ‘
>>> text
[‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘ZZZ‘, ‘C‘], ‘e‘, ‘f‘]
>>> text_copy     #并没有修改text_copy的内容,但是却被更改。证明这个copy 是浅拷贝
[‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘ZZZ‘, ‘C‘], ‘e‘, ‘f‘]

在列表嵌套列表的存储中,实际存的是子列表的指针,浅拷贝拷贝的也是相应子列表指针,所以更改子列表元素原列表和复制列表都会改变。

>>> text_copy[4][0] = ‘Yang‘
>>> text
[‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘Yang‘, ‘ZZZ‘, ‘C‘], ‘e‘, ‘f‘]
>>> text_copy
[‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘Yang‘, ‘ZZZ‘, ‘C‘], ‘e‘, ‘f‘]

 深层拷贝:

import copy  #拷贝模块
text = [‘a‘,‘b‘,‘c‘,‘d‘,[‘A‘,‘B‘,‘C‘],‘e‘,‘f‘]
print("     text=",text)
text_copy = copy.deepcopy(text)  #深层拷贝
print("text_copy=",text_copy)

text[4][1] = "ZZZ"
print("Chang text:      text=",text)
print("Chang text: text_copy=",text_copy)

text_copy[4][0] = "Yang"
print("Chang text_copy:      text=",text)
print("Chang text_copy: text_copy=",text_copy)

输出:
     text= [‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘B‘, ‘C‘], ‘e‘, ‘f‘]
text_copy= [‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘B‘, ‘C‘], ‘e‘, ‘f‘]
Chang text:      text= [‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘ZZZ‘, ‘C‘], ‘e‘, ‘f‘]
Chang text: text_copy= [‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘B‘, ‘C‘], ‘e‘, ‘f‘]
Chang text_copy:      text= [‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘A‘, ‘ZZZ‘, ‘C‘], ‘e‘, ‘f‘]
Chang text_copy: text_copy= [‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘Yang‘, ‘B‘, ‘C‘], ‘e‘, ‘f‘]

深拷贝是完全拷贝,子列表也重新保存。

浅拷贝三种:

p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)

统计:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘Amy‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]
>>> names.count("Amy")
2

排序&翻转:

>>> names
[‘Alex‘, ‘Tenglan‘, ‘Amy‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]
>>> names.sort() #排序
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()   #3.0里不同数据类型不能放在一起排序了,擦
>>> names[-3] = ‘1‘
>>> names[-2] = ‘2‘
>>> names[-1] = ‘3‘
>>> names
[‘Alex‘, ‘Amy‘, ‘Amy‘, ‘Tenglan‘, ‘Tom‘, ‘1‘, ‘2‘, ‘3‘]
>>> names.sort()
>>> names
[‘1‘, ‘2‘, ‘3‘, ‘Alex‘, ‘Amy‘, ‘Amy‘, ‘Tenglan‘, ‘Tom‘]

>>> names.reverse() #反转
>>> names
[‘Tom‘, ‘Tenglan‘, ‘Amy‘, ‘Amy‘, ‘Alex‘, ‘3‘, ‘2‘, ‘1‘]

获取下标:

>>> names
[‘Tom‘, ‘Tenglan‘, ‘Amy‘, ‘Amy‘, ‘Alex‘, ‘3‘, ‘2‘, ‘1‘]
>>> names.index("Amy")
2 #只返回找到的第一个下标

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable‘s items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -- append object to end """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]

                   Use of negative indices is not supported.
        """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]

                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable‘s items
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y

                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

list

功能源码

原文地址:https://www.cnblogs.com/yz9110/p/8191144.html

时间: 2024-11-08 23:16:24

Python基础(二)之数据类型和运算(4)—— 列表的相关文章

Python基础之基本数据类型一《数字与字符串》

一.运算符 结果是值 算数运算                            a = 10 * 10                  赋值运算                            a = a + 1    a+=1 结果是布尔值 比较运算                            a = 1 > 5                  逻辑运算                            a = 1>6 or 1==1              

Python基础二:pycharm的安装及简单使用,while循环,格式化输出,运算符, 编码的初识,git

Python基础二: pycharm的安装及简单使用,while循环,格式化输出,运算符, 编码的初识,git 1.pycharm的安装及简单使用 Tab / Shift + Tab 缩进.不缩进当前行 (先选中代码) Shift + 滚轮 放大缩小代码 Ctrl + ? 注释.解注(先选中代码) Ctrl + d 复制上一行代码 Ctrl + z 撤销 Ctrl + Shift + F10 RUN Ctrl + 左键---->点击 int,str 等可查看源码 2.while 循环(重点) w

Python基础二--基本控制语句

基本接触每一种语言,都需要做的:1.print 一个"Hello world!" 2.了解基本的数据类型 3.学习控制语句. 当我们学习控制语句,一般都离不开if,for ,while,switch(case).本文就做一个简单的介绍python的基本控制语句,其中我们用if while来做一个经典的"猜数字游戏",if for来做一个"输出完美数". 在此之前,对于一些没用过python的同学而熟悉c/c++等用{}来做块的要注意了,pytho

二.Python基础语法和数据类型

Python第二节 基础语法和数据类型 Python编码 python3默认情况下源码文件以UTF-8编码, 字符串均为unicode字符串.同时也可以通过# -*- coding: cp-1252 -*-这样类似的代码进行源码编码的变更. Python标志符 第一个字符必须是字母或者下划线"_", 绝对不能是数字或其他特殊字符. 其他字符: 任意什么都行 可以使用中文做变量名 标识符对大小写敏感 Python关键字 关键字禁止被用作任何标识符名称. 可通过标准库的keyword模块查

进击的Python【第二章】:Python基础(二)

Python基础(二) 本章内容 数据类型 数据运算 列表与元组的基本操作 字典的基本操作 字符编码与转码 模块初探 练习:购物车程序 一.数据类型 Python有五个标准的数据类型: Numbers(数字) String(字符串) List(列表) Tuple(元组) Dictionary(字典) 1. Number(数字) number类型用来专门存储数字数据,他们是不可改变的数据类型,这意味着改变数字数据类型会分配一个新的对象 Python支持四种不同的数字类型: int(有符号整型) l

python笔记二(数据类型和变量、字符串和编码)

一.数据类型 python可以直接处理的数据类型有:整数.浮点数.字符串.布尔值.空值. 整数 浮点数 字符串:双引号内嵌套单引号,可以输出 i'm ok. 也可以用\来实现,\n 换行 \t table 多行字符串用  ''' ''' 布尔值: 可以对布尔值进行与或非运算/ 与and 或or 非not 空值 二.变量 a = 1/ a = "nadech"    与java不同,python在声明一个变量的时候不用指定变量的类型,直接赋值就可以了 在 执行a =1 的时候,pytho

python基础(9):基本数据类型四(set集合)、基础数据类型补充、深浅拷贝

1. 基础数据类型补充 li = ["李嘉诚", "麻花藤", "?海峰", "刘嘉玲"] s = "_".join(li) print(s) li = "?花?闺?" s = "_".join(li) print(s) 列表: 循环删除列表中的每?个元素 li = [11, 22, 33, 44] for e in li: li.remove(e) print(li

Python基础学习参考(六):列表和元组

一.列表 列表是一个容器,里面可以放置一组数据,并且列表中的每个元素都具有位置索引.列表中的每个元素是可以改变的,对列表操作都会影响原来的列表.列表的定义通过"[ ]"来定义,元素之间用逗号隔开,举例如下: a = [12,'hello',15.5,True] 上面就定义了一个列表,列表中的元素可以是任意数据类型,并不仅限于例子中的这些数据类型. 1.访问列表中的元素 最直接的方式就是通过位置索引来访问元素,列表的索引是从0开始的.比如想访问上面列表中的第一个元素,并打印出来: pri

Python基础学习笔记(六)常用列表操作函数和方法

参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-lists.html 3. http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000 常用操作列表的内置函数: 序号 函数 1 cmp(list1, list2)比较两个列表的元素 2 len(list)列表元素个数 3 max(list)返回列表元素最大值 4 mi

python基础二(基础数据类型)

一,引子. 1 什么是数据? x=10,10是我们要存储的数据 2 为何数据要分不同的类型 数据是用来表示状态的,不同的状态就应该用不同的类型的数据去表示 3 数据类型 数字 字符串 列表 元组 字典 集合 二基础数据类型. 2.1数字int. 数字主要是用于计算用的,使用方法并不是很多,就记住一种就可以: #bit_length() 当十进制用二进制表示时,最少使用的位数 v = 11 data = v.bit_length() print(data) 2.2布尔值bool. 布尔值就两种:T