澳门新萄京官方网站-www.8455.com-澳门新萄京赌场网址

澳门新萄京官方网站:读书笔记,列表和元组

2019-10-30 作者:www.8455.com   |   浏览(50)

列表函数

列表(list):

  1. list函数能够将字符串转变为列表
  2. ' '.join(somelist)能够将列表调换为字符串
  3. 从列表中去除成分得以接受del语句来落到实处
  4. 主意是与对象有紧凑联系的函数:对象.方法(参数)
  5. append方法用于在列表末尾追加新的对象
  6. count方法总计有些成分在列表中冒出的次数
  7. extend方法能够在列表的末尾二次性追加另贰个队列中的多个值,如 a.extend(b)
  8. index方法用于从列表中找寻有个别值第八个相配项的目录地点
  9. insert方法用于将对象插入到列表中

    >>> numbers = [1, 2, 3, 5, 6, 7]
    >>> numbers.insert(3, 'four')
    

     

  10. pop方法会移除列表中的贰个成分(暗中认可是最后二个),并且重临该因素的值

  11. remove方法用于移除列表中有个别值的率先个匹配项
  12. reverse方法将列表中的成分反向寄放
  13. 复制整个列表用y = x[:],直接把x赋值给y是没用的
  14. sort方法退换了原本的列表,sorted函数不转移,再次回到别本
  15. sort方法有其余多个可选的参数——key和reverse

    >>> x.sort(key=len)
    >>> x.sort(reverse=True)
    

     

  16. tuple函数的功能与list函数基本上是千篇大器晚成律的:以二个行列作为参数并把它调换为元组

增添和强盛

  表明:列表是最常用的Python数据类型,它能够当做八个方括号内的逗号分隔值出现。列表的数量项没有须求具备相似的花色。创造多少个列表,只要把逗号分隔的例外的数码项应用方括号括起来就可以。

列表的数量项无需全部相近的项目。列表中的各类成分都分配贰个数字 - 它的职分,或索引,第一个索引是0,第4个目录是1,以此类推。
Python有6个种类的停放类型,但最广泛的是列表和元组。种类都得以张开的操作包涵索引,切条,加,乘,检查成员。其余,Python已经停放鲜明体系的尺寸以至分明最大和纤维的要素的诀窍。

list.append() 在列表末尾追加新的靶子

  示例:

 

 1 >>> dir(list)  #dir 查看列表的函数
 2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
 3 >>> help(list.append) #help 查看 list.append() 函数的详细内容
 4 Help on method_descriptor:
 5 
 6 append(...)
 7     L.append(object) -- append object to end  #将对象追加到末尾
 8 
 9 >>> a =[2,6]
10 >>> a.append(50)  #将对象50追加到列表a中
11 >>> a
12 [2, 6, 50]
13 >>> a.append("python book") 
14 >>> a
15 [2, 6, 50, 'python book']
16 >>> a
17 [2, 6, 50, 'python book', ['baidu', 'weibo']]
18 >>> b =[1]
19 >>> id(b)   #id 返回值给出在内存中的空间
20 60126664L
21 >>> b.append(5)
22 >>> b
23 [1, 5]
24 >>> b
25 [1, 5]
26 >>> id(b) #追加5 之后,id返回值 一样
27 60126664L
28 >>> b.append("zhangsan")
29 >>> id(b)
30 60126664L
31 >>> b
32 [1, 5, 'zhangsan']
33 >>>
注:列表在被修改的时候,不是创建了一个新的列表,而是修改了原来的列表,这种修改称为原地修改

    name_list1 = ['physics', 'chemistry', 1997, 2000]

Python列表操作的函数和章程
列表操作包罗以下函数:
1、cmp(list1, list2):比较五个列表的要素 
2、len(list):列表成分个数 
3、max(list):重返列表成分最大值 
4、min(list):再次来到列表成分最小值 
5、list(seq):将元组调换为列表 
列表操作包括以下格局: 1、list.append(obj):在列表末尾增添新的指标
2、list.count(obj):总结有个别成分在列表中出现的次数
3、list.extend(seq):在列表末尾一遍性追加另三个体系中的八个值(用新列表扩张原来的列表)
4、list.index(obj):从列表中寻觅有些值第二个相称项的目录地方
5、list.insert(index, obj):将指标插入列表
6、list.pop(obj=list[-1]):移除列表中的一个成分(默许最后八个成分),並且重回该因素的值
7、list.remove(obj):移除列表中有个别值的首先个相称项
8、list.reverse():反向列表相月素
9、list.sort([func]):对原列表举行排序

extend()在列表末尾贰遍性追加另五个行列中的几个值(用新列表扩展原本的列表)

    name_list2 = [1, 2, 3, 4, 5 ]

 1 >>> help(list.extend) #help查看list.extend函数的详细内容
 2 Help on method_descriptor:
 3 
 4 extend(...)
 5     L.extend(iterable) -- extend list by appending elements from the iterable  #把可迭代对象中的元素追加到列表中
 6 
 7 >>> a=[1,2,3]  #可迭代对象
 8 >>> b=[4,5,6]  #可迭代对象
 9 >>> a.extend(b) 
10 >>> a           #b列表中的元素被一个个追加到a列表中
11 [1, 2, 3, 4, 5, 6] 
12 >>> a.extend("python")
13 >>> a
14 [1, 2, 3, 4, 5, 6, 'p', 'y', 't', 'h', 'o', 'n']
15 >>> alst =[1,2]20 >>> hasattr(alst,'__iter__') #判断是否可迭代,是返回true ,否则false
21 True
22 >>> hasattr("python",'__iter__') #字符串不可迭代,此处是将字符串一个的字符拆出追加
23 False
24 >>> a =[1,2]
25 >>> a.append([4,5])
26 >>> a
27 [1, 2, [4, 5]]
28 >>> a.extend([4,5]) 
29 >>> a
30 [1, 2, [4, 5], 4, 5]
31 >>> b =[9,8]
32 >>> a.append(b[0])
33 >>> a.append(b[1])
34 >>> a
35 [1, 2, [4, 5], 4, 5, 9, 8]
36 >>>
注:append 与extend 区别就是,extend 将一个个的元素拆分追加,append是整体追加

    name_list3 = ["a", "b", "c", "d"]

此外函数

基本操作:

count() 总计有个别成分在列表中冒出的次数

  • 索引
  • 澳门新萄京官方网站:读书笔记,列表和元组。切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 澳门新萄京官方网站:读书笔记,列表和元组。包含
 1 >>> help(list.count)
 2 Help on method_descriptor:
 3 
 4 count(...)
 5     L.count(value) -> integer -- return number of occurrences of value  #返回出现的次数
 6 
 7 >>> a =[1,1,1,2,2,2,3,3,3]
 8 >>> a.count(1)   #1这个元素在列表中出现3次
 9 3
10 >>> a.count(2)  #2这个元素在列表中出现3次
11 3
12 >>> a.count("a") #a在列表中没有
13 0

澳门新萄京官方网站 1澳门新萄京官方网站 2

index() 从列表中找寻有个别值第1个相称项的目录地方

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) -> None -- append object to end """
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []

    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) -> None -- 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) -> None -- 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, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self value. """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

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

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __iadd__(self, *args, **kwargs): # real signature unknown
        """ Implement self =value. """
        pass

    def __imul__(self, *args, **kwargs): # real signature unknown
        """ Implement self*=value. """
        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, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

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

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

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

    __hash__ = None
 1 >>> help(list.index)
 2 Help on method_descriptor:
 3 
 4 index(...)
 5     L.index(value, [start, [stop]]) -> integer -- return first index of value. #参数中的value值在列表中第一次出现的索引位置
 6     Raises ValueError if the value is not present.
 7 
 8 >>> a.index(1)
 9 0
10 >>> a.index(2)
11 3
12 >>>

list

insert() 将对象插入列表

常用功用:

 1 >>> help(list.insert)
 2 Help on method_descriptor:
 3 
 4 insert(...)
 5     L.insert(index, object) -- insert object before index  #把对象插入到索引所对应的元素的前面
 6 
 7 >>> a =["python","web"]
 8 >>> a.insert(1,"aaa")   #在索引是1的元素的前面插入一个字符串aa
 9 >>> a
10 ['python', 'aaa', 'web']
11 >>> a.insert(0,"like") #在最前面插入一个字符串like
12 >>> a
13 ['like', 'python', 'aaa', 'web']
14 >>>
注:insert为原地修改,没有新建一个列表

目录示例:

pop() 移除列表中的四个因素(私下认可最终贰个因素),而且重临该因素的值

name_list = ['one','two','three']
print(name_list[0])
print(name_list[1])
print(name_list[2])

运行结果:
one
two
three
 1 >>> help(list.pop)
 2 Help on method_descriptor:
 3 
 4 pop(...)
 5     L.pop([index]) -> item -- remove and return item at index (default last).  #删除索引所对应的元素,并它作为返回值返回 (默认删除最后一个元素)
 6     Raises IndexError if list is empty or index is out of range. #不能删除为空的或者超出索引范围的元素,否则索引错误
 7 
 8 >>> a
 9 ['like', 'python', 'aaa', 'web']
10 >>> a.pop(1)
11 'python'
12 >>> a
13 ['like', 'aaa', 'web']
14 >>>

 

remove() 移除列表中有些值的率先个相称项

目录删除示例:

 1 >>> help(list.remove)
 2 Help on method_descriptor:
 3 
 4 remove(...)
 5     L.remove(value) -- remove first occurrence of value.  #移除某个值得第一个匹配项
 6     Raises ValueError if the value is not present.
 7 
 8 >>> a =["test","test","demo"]
 9 >>> a.remove("test")
10 >>> a
11 ['test', 'demo']
12 >>> a.remove("aa")
13 Traceback (most recent call last):
14   File "<stdin>", line 1, in <module>
15 ValueError: list.remove(x): x not in list
16 >>>
name_list = ['one','two','three']
del name_list[1]
print(name_list)

运行结果:
['one', 'three']

reverse()  反向列表瓜时素

 

 1 >>> help(list.reverse)
 2 Help on method_descriptor:
 3 
 4 reverse(...)
 5     L.reverse() -- reverse *IN PLACE*
 6 
 7 >>> a =[1,2,3,4,5]
 8 >>> a.reverse()
 9 >>> a
10 [5, 4, 3, 2, 1]
11 >>>

切开示例:

sort() 对原列表进行排序

name_list = ['one','two','three']
print(name_list[0:2])
print(name_list[2:len(name_list)])

运行结果:
['one', 'two']
['three']
 1 >>> help(list.sort)
 2 Help on method_descriptor:
 3 
 4 sort(...)
 5     L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 6     cmp(x, y) -> -1, 0, 1
 7 
 8 >>> a =[5,9,3,1]
 9 >>> a.sort()  #从小到大排列
10 >>> a
11 [1, 3, 5, 9]
12 >>> b=[9,3,8,6]
13 >>> b.sort(reverse=True) #从大到小排列
14 >>> b
15 [9, 8, 6, 3]
16 >>>

 

切开删除示例:

name_list = ['one','two','three']
del name_list[1:3]
print(name_list)

运行结果:
['one']

* *

for循环示例:

name_list = ['one','two','three']
for i in name_list:
    print(i)

运行结果:
one
two
three

 

列表内部提供的其余作用:

append(self, p_object):

  表达:用于在列表末尾加多新的对象。p_object:追加的对象。(再次回到None)

  示例:

name_list1= ['one','two','three']
name_list2= ['one','two','three']
name_list3= ['one','two','three']
name_list1.append('four')
name_list2.append(['1','2','3'])
name_list3.append(4)
print(name_list1)
print(name_list2)
print(name_list3)

运行结果:
['one', 'two', 'three', 'four']
['one', 'two', 'three', ['1', '2', '3']]
['one', 'two', 'three', 4]
  • 列表可含蓄其余数据类型的因素,单个列表中的元素无须全为同意气风发种类。
  • 只向列表的尾巴部分增多一个新的要素。

 

count(self,value):

  表达:总括列表中有些对象现身的次数。value:要总结的靶子。(重返int)

  示例:

name_list1= ['one','two','three']
name_list1.append('four')
name_list1.append('four')
name_list1.append('four')
print(name_list1)
print(name_list1.count('four'))

运行结果:
['one', 'two', 'three', 'four', 'four', 'four']
3

 

extend(self, iterable):

  表达:在列表末尾二次性追加另一个队列中的多个值(用新列表扩大原来的列表)。iterable(可迭代的):增添的对象(再次来到None)

  示例:

aList = [123, 'xyz', 'zara', 'abc', 123]
bList = [2009, 'manni']
aList.extend(bList)

print ("Extended List : ", aList)

运行结果:
Extended List :  [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

 

index(self, value, start=None, end=None):

  表明:从列表中找寻有个别值第一个相称项的目录地点。value:查找相配项。start:发轫地方(从0伊始),默以为无。end:结束地点,默以为无。(重返int)

  示例:

aList = [123, 'xyz', 'zara', 'abc', 123]
print(aList.index(123))

运行结果:
0

 

insert(self, index, p_object):

  表达:用于将点名对象插入列表的钦点地点。index:地点。p_object:插入的对象。

  示例:

aList = [123, 'xyz', 'zara', 'abc', 123]
aList.insert(1,'SB')
print(aList)

运行结果:
[123, 'SB', 'xyz', 'zara', 'abc', 123]

 

pop(self, index=None):

  表达:移除列表中的一个要素(暗中认可最终叁个成分),并且再次来到该因素的值。index:移除成分的义务,默以为无。(重回移除的要素的值)

  示例:

aList = [123, 'xyz', 'zara', 'abc', 123]
aList.pop(2)
print(aList)

运行结果:
[123, 'xyz', 'abc', 123]

 

remove(self, value):

  表明:移除列表中有些值的第三个相配项。value:移除的首先个相配元素。(再次来到None)

   示例:

aList = [123, 'xyz', 'zara', 'abc', 123]
aList.remove('xyz')
print(aList)

运行结果:
[123, 'zara', 'abc', 123]

 

reverse(self):

  表达:反向列表七月素。

  示例:

aList = [123, 'xyz', 'zara', 'abc', 567]
aList.reverse()
print(aList)

运行结果:
[567, 'abc', 'zara', 'xyz', 123]

 

sort(self, key=None, reverse=Flase):

  表明:对原列表实行排序,假如内定参数,则接纳比较函数钦赐的相比较函数。

  示例:

aList = [ 'xyz', 'zara', 'abc', 'xyz']
aList.sort()
print ("List : ", aList)

运行结果:
List :  ['abc', 'xyz', 'xyz', 'zara']

 

本文由澳门新萄京官方网站发布于www.8455.com,转载请注明出处:澳门新萄京官方网站:读书笔记,列表和元组

关键词: