python基础知识-列表,元组,字典

列表(list)

赋值方法:

l = [11,45,67,34,89,23]

l = list()

列表的方法:

 1 #!/usr/bin/env python
 2
 3 class list(object):
 4     """
 5     list() -> new empty list
 6     list(iterable) -> new list initialized from iterable‘s items
 7     """
 8     def append(self, p_object): # real signature unknown; restored from __doc__
 9         ‘‘‘在列表末尾添加一个新的对象‘‘‘
10         """ L.append(object) -> None -- append object to end """
11         pass
12
13     def clear(self): # real signature unknown; restored from __doc__
14         ‘‘‘清空列表中的所有对象‘‘‘
15         """ L.clear() -> None -- remove all items from L """
16         pass
17
18     def copy(self): # real signature unknown; restored from __doc__
19         ‘‘‘拷贝一个新的列表‘‘‘
20         """ L.copy() -> list -- a shallow copy of L """
21         return []
22
23     def count(self, value): # real signature unknown; restored from __doc__
24         ‘‘‘某个元素在列表中出现的次数‘‘‘
25         """ L.count(value) -> integer -- return number of occurrences of value """
26         return 0
27
28     def extend(self, iterable): # real signature unknown; restored from __doc__
29         ‘‘‘在列表的末尾追加另外一个列表的多个值‘‘‘
30         """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
31         pass
32
33     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
34         ‘‘‘查找给定值第一次出现的位置‘‘‘
35         """
36         L.index(value, [start, [stop]]) -> integer -- return first index of value.
37         Raises ValueError if the value is not present.
38         """
39         return 0
40
41     def insert(self, index, p_object): # real signature unknown; restored from __doc__
42         ‘‘‘指定位置插入元素‘‘‘
43         """ L.insert(index, object) -- insert object before index """
44         pass
45
46     def pop(self, index=None): # real signature unknown; restored from __doc__
47         ‘‘‘移除列表中最后一个元素,并获取这个元素‘‘‘
48         """
49         L.pop([index]) -> item -- remove and return item at index (default last).
50         Raises IndexError if list is empty or index is out of range.
51         """
52         pass
53
54     def remove(self, value): # real signature unknown; restored from __doc__
55         ‘‘‘移除列表中给定值的第一次出现的元素‘‘‘
56         """
57         L.remove(value) -> None -- remove first occurrence of value.
58         Raises ValueError if the value is not present.
59         """
60         pass
61
62     def reverse(self): # real signature unknown; restored from __doc__
63         ‘‘‘反转列表‘‘‘
64         """ L.reverse() -- reverse *IN PLACE* """
65         pass
66
67     def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
68         ‘‘‘对列表中的元素排序‘‘‘
69         """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
70         pass

list

方法示例:

####

append()

>>> l = [11,45,67,34,89,23]

>>> l.append(44)

>>> l

[11, 45, 67, 34, 89, 23, 44]

####

>>> l

[1, 4, 7, 11, 23, 34, 34, 44, 44, 45, 67, 89]

>>> l.clear()

>>> l

[]

####

copy()

>>> l

[11, 45, 67, 34, 89, 23, 44]

>>> i = l.copy()

>>> i

[11, 45, 67, 34, 89, 23, 44]

####

count()

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34]

>>> l.count(44)

3

####

extend()

>>> i = [1,4,7,6]

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34]

>>> l.extend(i)

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34, 1, 4, 7, 6]

####

indexi()

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34, 1, 4, 7, 6]

>>> l.index(44)

6

>>> l.index(45)

1

####

pop()

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34, 1, 4, 7, 6]

>>> l.pop()

6

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34, 1, 4, 7]

####

remove()

>>> l

[11, 45, 67, 34, 89, 23, 44, 44, 44, 45, 34, 1, 4, 7]

>>> l.remove(45)

>>> l

[11, 67, 34, 89, 23, 44, 44, 44, 45, 34, 1, 4, 7]

>>> l.remove(44)

>>> l

[11, 67, 34, 89, 23, 44, 44, 45, 34, 1, 4, 7]

####

reverse()

>>> l

[11, 67, 34, 89, 23, 44, 44, 45, 34, 1, 4, 7]

>>> l.reverse()

>>> l

[7, 4, 1, 34, 45, 44, 44, 23, 89, 34, 67, 11]

####

sort()

>>> l

[7, 4, 1, 34, 45, 44, 44, 23, 89, 34, 67, 11]

>>> l.sort()

>>> l

[1, 4, 7, 11, 23, 34, 34, 44, 44, 45, 67, 89]

####

元组:

元组中的元素是不可以改变的。

赋值方法:

tup = ‘a‘,‘b‘,‘c‘

tup = (‘a‘, ‘b‘, ‘c‘)

元组的方法:

  1 #!/usr/bin/env python
  2 class tuple(object):
  3     """
  4     tuple() -> empty tuple
  5     tuple(iterable) -> tuple initialized from iterable‘s items
  6
  7     If the argument is a tuple, the return value is the same object.
  8     """
  9     def count(self, value): # real signature unknown; restored from __doc__
 10         ‘‘‘某个元素在元素中出现的次数‘‘‘
 11         """ T.count(value) -> integer -- return number of occurrences of value """
 12         return 0
 13
 14     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 15         ‘‘‘查找给定值第一次出现的位置‘‘‘
 16         """
 17         T.index(value, [start, [stop]]) -> integer -- return first index of value.
 18         Raises ValueError if the value is not present.
 19         """
 20         return 0
 21
 22     def __add__(self, *args, **kwargs): # real signature unknown
 23         """ Return self+value. """
 24         pass
 25
 26     def __contains__(self, *args, **kwargs): # real signature unknown
 27         """ Return key in self. """
 28         pass
 29
 30     def __eq__(self, *args, **kwargs): # real signature unknown
 31         """ Return self==value. """
 32         pass
 33
 34     def __getattribute__(self, *args, **kwargs): # real signature unknown
 35         """ Return getattr(self, name). """
 36         pass
 37
 38     def __getitem__(self, *args, **kwargs): # real signature unknown
 39         """ Return self[key]. """
 40         pass
 41
 42     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 43         pass
 44
 45     def __ge__(self, *args, **kwargs): # real signature unknown
 46         """ Return self>=value. """
 47         pass
 48
 49     def __gt__(self, *args, **kwargs): # real signature unknown
 50         """ Return self>value. """
 51         pass
 52
 53     def __hash__(self, *args, **kwargs): # real signature unknown
 54         """ Return hash(self). """
 55         pass
 56
 57     def __init__(self, seq=()): # known special case of tuple.__init__
 58         """
 59         tuple() -> empty tuple
 60         tuple(iterable) -> tuple initialized from iterable‘s items
 61
 62         If the argument is a tuple, the return value is the same object.
 63         # (copied from class doc)
 64         """
 65         pass
 66
 67     def __iter__(self, *args, **kwargs): # real signature unknown
 68         """ Implement iter(self). """
 69         pass
 70
 71     def __len__(self, *args, **kwargs): # real signature unknown
 72         """ Return len(self). """
 73         pass
 74
 75     def __le__(self, *args, **kwargs): # real signature unknown
 76         """ Return self<=value. """
 77         pass
 78
 79     def __lt__(self, *args, **kwargs): # real signature unknown
 80         """ Return self<value. """
 81         pass
 82
 83     def __mul__(self, *args, **kwargs): # real signature unknown
 84         """ Return self*value.n """
 85         pass
 86
 87     @staticmethod # known case of __new__
 88     def __new__(*args, **kwargs): # real signature unknown
 89         """ Create and return a new object.  See help(type) for accurate signature. """
 90         pass
 91
 92     def __ne__(self, *args, **kwargs): # real signature unknown
 93         """ Return self!=value. """
 94         pass
 95
 96     def __repr__(self, *args, **kwargs): # real signature unknown
 97         """ Return repr(self). """
 98         pass
 99
100     def __rmul__(self, *args, **kwargs): # real signature unknown
101         """ Return self*value. """
102         pass

tuple

方法示例:

####

count()

>>> tup = (‘a‘,‘b‘,‘c‘,‘b‘)
>>> tup.count(‘b‘)
2

####

index()

>>> tup = (‘a‘,‘b‘,‘c‘,‘b‘)

>>> tup.index(‘b‘)
1

###

字典:

字典(dict):字典为一对键(key)和值(value)的对应关系,中间使用“:”分隔开。

key在字典中是唯一的,字典是无序的。

赋值字典:

dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

字典的方法:

  1 #!/usr/bin/env python
  2 class dict(object):
  3     """
  4     dict() -> new empty dictionary
  5     dict(mapping) -> new dictionary initialized from a mapping object‘s
  6         (key, value) pairs
  7     dict(iterable) -> new dictionary initialized as if via:
  8         d = {}
  9         for k, v in iterable:
 10             d[k] = v
 11     dict(**kwargs) -> new dictionary initialized with the name=value pairs
 12         in the keyword argument list.  For example:  dict(one=1, two=2)
 13     """
 14     def clear(self): # real signature unknown; restored from __doc__
 15         ‘‘‘清空字典‘‘‘
 16         """ D.clear() -> None.  Remove all items from D. """
 17         pass
 18
 19     def copy(self): # real signature unknown; restored from __doc__
 20         ‘‘‘拷贝字典,浅拷贝‘‘‘
 21         """ D.copy() -> a shallow copy of D """
 22         pass
 23
 24     @staticmethod # known case
 25     def fromkeys(*args, **kwargs): # real signature unknown
 26         ‘‘‘首先有一个列表,这个列表将作为一个字典的key,如果不给值则所有key的值为空,如果给值就将值设置为key的值‘‘‘
 27         """ Returns a new dict with keys from iterable and values equal to value. """
 28         pass
 29
 30     def get(self, k, d=None): # real signature unknown; restored from __doc__
 31         ‘‘‘根据key取值,如果没有这个key,不返回值‘‘‘
 32         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
 33         pass
 34
 35     def items(self): # real signature unknown; restored from __doc__
 36         ‘‘‘所有key和值组成列表的形式‘‘‘
 37         """ D.items() -> a set-like object providing a view on D‘s items """
 38         pass
 39
 40     def keys(self): # real signature unknown; restored from __doc__
 41         ‘‘‘所有key组成列表的形式‘‘‘
 42         """ D.keys() -> a set-like object providing a view on D‘s keys """
 43         pass
 44
 45     def pop(self, k, d=None): # real signature unknown; restored from __doc__
 46         ‘‘‘获取key的值,并从字典中删除‘‘‘
 47         """
 48         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 49         If key is not found, d is returned if given, otherwise KeyError is raised
 50         """
 51         pass
 52
 53     def popitem(self): # real signature unknown; restored from __doc__
 54         ‘‘‘获取键值对,并在字典中删除,随机的‘‘‘
 55         """
 56         D.popitem() -> (k, v), remove and return some (key, value) pair as a
 57         2-tuple; but raise KeyError if D is empty.
 58         """
 59         pass
 60
 61     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
 62         ‘‘‘如果key不存在,则创建,如果key存在则返回key的值,不会修改key的值‘‘‘
 63         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
 64         pass
 65
 66     def update(self, E=None, **F): # known special case of dict.update
 67         ‘‘‘更新‘‘‘
 68         """
 69         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 70         If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 71         If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 72         In either case, this is followed by: for k in F:  D[k] = F[k]
 73         """
 74         pass
 75
 76     def values(self): # real signature unknown; restored from __doc__
 77         ‘‘‘所有值的列表形式‘‘‘
 78         """ D.values() -> an object providing a view on D‘s values """
 79         pass
 80
 81     def __contains__(self, *args, **kwargs): # real signature unknown
 82         """ True if D has a key k, else False. """
 83         pass
 84
 85     def __delitem__(self, *args, **kwargs): # real signature unknown
 86         """ Delete self[key]. """
 87         pass
 88
 89     def __eq__(self, *args, **kwargs): # real signature unknown
 90         """ Return self==value. """
 91         pass
 92
 93     def __getattribute__(self, *args, **kwargs): # real signature unknown
 94         """ Return getattr(self, name). """
 95         pass
 96
 97     def __getitem__(self, y): # real signature unknown; restored from __doc__
 98         """ x.__getitem__(y) <==> x[y] """
 99         pass
100
101     def __ge__(self, *args, **kwargs): # real signature unknown
102         """ Return self>=value. """
103         pass
104
105     def __gt__(self, *args, **kwargs): # real signature unknown
106         """ Return self>value. """
107         pass
108
109     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
110         """
111         dict() -> new empty dictionary
112         dict(mapping) -> new dictionary initialized from a mapping object‘s
113             (key, value) pairs
114         dict(iterable) -> new dictionary initialized as if via:
115             d = {}
116             for k, v in iterable:
117                 d[k] = v
118         dict(**kwargs) -> new dictionary initialized with the name=value pairs
119             in the keyword argument list.  For example:  dict(one=1, two=2)
120         # (copied from class doc)
121         """
122         pass
123
124     def __iter__(self, *args, **kwargs): # real signature unknown
125         """ Implement iter(self). """
126         pass
127
128     def __len__(self, *args, **kwargs): # real signature unknown
129         """ Return len(self). """
130         pass
131
132     def __le__(self, *args, **kwargs): # real signature unknown
133         """ Return self<=value. """
134         pass
135
136     def __lt__(self, *args, **kwargs): # real signature unknown
137         """ Return self<value. """
138         pass
139
140     @staticmethod # known case of __new__
141     def __new__(*args, **kwargs): # real signature unknown
142         """ Create and return a new object.  See help(type) for accurate signature. """
143         pass
144
145     def __ne__(self, *args, **kwargs): # real signature unknown
146         """ Return self!=value. """
147         pass
148
149     def __repr__(self, *args, **kwargs): # real signature unknown
150         """ Return repr(self). """
151         pass
152
153     def __setitem__(self, *args, **kwargs): # real signature unknown
154         """ Set self[key] to value. """
155         pass
156
157     def __sizeof__(self): # real signature unknown; restored from __doc__
158         """ D.__sizeof__() -> size of D in memory, in bytes """
159         pass
160
161     __hash__ = None

dict

方法示例:

####

clear()

>>> dic

{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘}

>>> dic.clear()

>>> dic

{}

####

copy()

>>> dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

>>> dic2 = dic.copy()

>>> dic2

{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘}

####

>>> l = [2,3,5,6,7]

>>> d = dict.fromkeys(l)

>>> d

{2: None, 3: None, 5: None, 6: None, 7: None}

>>> d = dict.fromkeys(l,‘a‘)

>>> d

{2: ‘a‘, 3: ‘a‘, 5: ‘a‘, 6: ‘a‘, 7: ‘a‘}

####

items()

>>> dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

>>> dic.items()

dict_items([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)])

####

keys()

>>> dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

>>> dic.keys()

dict_keys([‘k1‘, ‘k2‘, ‘k3‘])

####

pop()

>>> dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

>>> dic.pop(‘k2‘)

‘v2‘

>>> dic

{‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘}

####

popitme()

>>> dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

>>> dic.popitem()

(‘k2‘, ‘v2‘)

>>> dic

{‘k1‘:‘v1‘,‘k3‘:‘v3‘}

####

setdefault()

>>> dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘,‘k3‘:‘v3‘}

>>> dic.setdefault(‘k2‘)

‘v2‘

>>> dic.setdefault(‘k4‘,‘v4‘)

‘v4‘

>>> dic

{‘k1‘: ‘v1‘, ‘k4‘: ‘v4‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘}

####

update()

>>> dic

{‘k1‘: ‘v1‘, ‘k4‘: ‘v4‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘}

>>> dic2

{‘k5‘: ‘v5‘}

>>> dic.update(dic2)

>>> dic

{‘k1‘: ‘v1‘, ‘k5‘: ‘v5‘, ‘k4‘: ‘v4‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘}

>>> dic2

{‘k5‘: ‘v5‘}

####

values()

>>> dic

{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘}

>>> dic.values()

dict_values([‘v1‘, ‘v2‘, ‘v3‘])

####

时间: 2024-12-25 12:52:11

python基础知识-列表,元组,字典的相关文章

[Python日记-2]列表-元组-字典-if-for

今天学习了列表,元组,字典相关知识,真的琐碎.我应该是学了好几遍了,刚开始是充满激情的,学到一个方法就迫不及待地去尝试,现在也平和了.好了,总结下. 1. 列表 Python中用方括号([])来表示列表,并用逗号来分隔其中的元素.要访问列表元素,列表的名称[索引]. 索引可以是负值,如将索引指定为-1,可让Python返回最后一个列表元素.可以在不明确列表长度的情况下,访问最后的元素. 1.1 列表中添加元素的方法: 1 Lis = [] 2 3 Lis.title() #使列表中每个元素的首字

Python数据结构之列表元组字典的用法

数据结构的含义 在学习数据结构之前,我们先来了解下数据结构的含义.数据结构是通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其他数据结构.在Python语言中,最基本的数据结构是序列(sequence).序列中的每个元素被分配一个序号----即元素的位置,称为索引或下标,索引从0开始递增. 典型的序列包括列表.元组和字符串.其中,列表是可变的(可修改),而元组和字符串是不可变的(一旦创建了就是固定的).列表.元组和字符串也是较常用的数据结构

python 数据类型 变量 列表 元组 字典 集合

Python中,能够直接处理的数据类型有以下几种: 整数 Python可以处理任意大小的整数,当然包括负整数,在程序中的表示方法和数学上的写法一模一样,例如:1,100,-8080,0,等等. 计算机由于使用二进制,所以,有时候用十六进制表示整数比较方便,十六进制用0x前缀和0-9,a-f表示,例如:0xff00,0xa5b4c3d2,等等. 浮点数 浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23x109和12.3x108是完全相等

python基础:列表、字典、元组、集合四种数据结构的方法以及使用整理

列表:shoplist = ['apple', 'mango', 'carrot', 'banana']字典:di = {'a':123,'b':'something'}集合:jihe = {'apple','pear','apple'}元组: t = 123,456,'hello' 1.列表    空列表:a=[]    函数方法:a.append(3)      >>>[3]              a.extend([3,4,5])     >>>[3,3,4,

Python基础2 列表、字典、集合

本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 names = ['Alex',"Tenglan",'Eric'] 通过下标访问列表中的元素,下标从0开始计数 >>> names[0] 'Alex' >>> names[2] 'Eric' >>> names[-1] 'Eric'

python基础知识4(字典和函数)

# 字典 - 又称为(# hash,映射,关联数组) - "字" ---> 先找首字母,查到这个字的解释所在的页数; ## 字典的定义: d = {} d = {"key1":"value1"} d = {"key1":"value1","key2":"value3"} d = { "172.25.254.1": { "user&q

python基础之列表,字典,集合

1,列表 (1) L1 =  [  ] # 创建空列表                    #需要注意的是,python和其他语言例如Java不一样,定义的时候不需要声明数据类型.具体原因是                        不用声明变量一样,Python不用去声明函数的返回类型,是由于其"若类型"的语言特性决定的.                        在其他语言中,例如C/C++语言中在存储一个数据之前,都需要在内存中给这个数据开辟一个固定的内存空间,   

python 基础知识四、字典

常见字典常量和操作 操作 解释 D = {} 空字典 D = {'spam':2 , 'egg':3} 两项目字典 D = {'food':{'ham':1,'egg':2}} 嵌套 D = dict.fromkeys(['a','b']) 其他构造技术 D = dict(zip(keylist, valslist)) 关键之.对应的对.键列表 D = dict(name='bob', age=42) D['eggs'] 以键进行索引运算 'eggs' in D  成员关系:键存在测试 D.ke

python基础知识-列表的排序问题

def main(): f=['orange','zoo','apple','internationalization','blueberry'] #python 内置的排序方式默认为升序(从小到大) #如果想要降序 用reverse参数来制定 #python中的函数几乎没有副作用的函数 #调用函数之后不会影响传入的参数 f2 = sorted (f,reverse=True) print(f) print(f2) f.reverse() f3=(reversed(f)) print(f3) f