python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文

一 大纲

2 运算符

3 基本数据类型

  整型:int

  字符串:str

  列表:list

  元组:tuple

  字典:dic

4 for enumrate xrange range

 

1.1. 列表中的十六进制或者unicode展示位中文

attr=(['CN', '0', '\xe6\xb5\x99\xe6\xb1\x9f', '\xe6\x9d\xad\xe5\xb7\x9e', 'ALIBABA'], ['CN', '0', 'qita', '0', 'cn'], ['\xe4\xb8\xad\xe5\x9b\xbd', '0', '\xe9\xa6\x99\xe6\xb8\xaf', '*', '\xe5\x85\xb6\xe4\xbb\x96'], ['CN', '*', '\xe5\x8c\x97\xe4\xba\xac', '\xe5\x8c\x97\xe4\xba\xac', '\xe9\x98\xbf\xe9\x87\x8c\xe4\xba\x91/\xe7\x94\xb5\xe4\xbf\xa1/\xe8\x81\x94\xe9\x80\x9a/\xe7\xa7\xbb\xe5\x8a\xa8/\xe9\x93\x81\xe9\x80\x9a/\xe6\x95\x99\xe8\x82\xb2\xe7\xbd\x91'])

        for i in attrs:
                s = str([j.decode("utf-8") for j in i]).replace('u\'','\'')
                print s.decode("unicode-escape")

  

有这样一个列表:

list = [{'channel_id': -3, 'name': u'\u7ea2\u5fc3\u5146\u8d6b'}, {u'seq_id': 0, u'name_en': u'Personal Radio', u'channel_id': 0, u'abbr_en': u'My', u'name': u'\u79c1\u4eba\u5146\u8d6b'}]



其中name值是中文,如何讲其显示为中文?

s = str(self.channel_list).replace('u\'','\'')
print s.decode("unicode-escape")


成功显示:

[{'channel_id': -3, 'name': '红心兆赫'}, {'seq_id': 0, 'name_en': 'Personal Radio', 'channel_id': 0, 'abbr_en': 'My', 'name': '私人兆赫'}, ]


但此时类型为unicode

>>> type(s)
<type 'unicode'>

  

 上节内容回顾

  1、编程语言
  2、python、C#、java
  3、python:pypy,cpython,jpython..
  4、执行方式
解释器
文件
  5、指定解释器
  python xxx.py
  ./xxx.py   #!/usr/bin/env python
  6、ascii   unicode   utf-8
  7、
    2.7    # -*- coding:utf-8 -*-
    3.x    默认utf-8
  8、变量,代指
    变量名 = 值
    变量名要求:
    a.数字字母下划线
    b.数字不能开头
    c.不能和py关键字重复
    a = "alex"
    b = a
  9、条件
    if 条件,elif 条件,else
  10、while
    while 条件,
    从上到下执行一次
    (判断条件是否真)从上到下执行一次
    (判断条件是否真)从上到下执行一次
    (判断条件是否真)从上到下执行一次
    (判断条件是否真)从上到下执行一次 

 

 

 

 

 二  前天作业讲解:

 知识点:

  判断奇偶:除以2取模

1 %
2 3%2=1
3 2%2=0
4 4%2=0

  详细见 url http://www.cnblogs.com/liujianzuo888/articles/5440915.html 

 三 编码转换

 

unicode 可以编译成 UTF-U GBK

 

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'Administrator'

a='刘建佐'        #默认是utf-8
a_unicod=a.decode('utf-8')  # decode是解码成unicode 括号是脚本内容的默认编码  即:将脚本内容的utf-8解码成unicode
a_gbk=a_unicod.encode('gbk') #encode是编码,将unicode的编码内容编码成指定的,这里是gbk
print(a_gbk)  #用于终端打印
#print(u"刘建佐")  #3里面是字符串  2里面是unicode 


# 3版本直接将utf-8编码成GBK 不需要先转成unicode了,因为3没有了

E:\py_test\s2_py>python3 test.py
Traceback (most recent call last):
File “test.py”, line 6, in <module>
a_unicod=a.decode(‘utf-8’) # decode是解码成unicode 括号是脚本内容的默认编码 即:将脚本内容的utf-8解码成unicode
AttributeError: ‘str’ object has no attribute ‘decode’

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 

 

四 pycharm 安装 配置

   file-setings-editor- file && file encode template  输入 

  

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'

 

五 pycharm 快捷键

   ctrl+/ 批量注释

  shift+方向键 选中 

  shift+tab 向左tab

六 运算符

算数运算:

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

比较运算:

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

赋值运算:

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

逻辑运算:

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

成员运算:

 《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

身份运算: 面向对象讲解

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 

运算符

名称

说明

例子

+

两个对象相加

3 + 5得到8。’a’ + ‘b’得到’ab’。

得到负数或是一个数减去另一个数

-5.2得到一个负数。50 – 24得到26。

*

两个数相乘或是返回一个被重复若干次的字符串

2 * 3得到6。’la’ * 3得到’lalala’。

**

返回x的y次幂

3 ** 4得到81(即3 * 3 * 3 * 3)

/

x除以y

4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333

//

取整除

返回商的整数部分

4 // 3.0得到1.0

%

取模

返回除法的余数

8%3得到2。-25.5%2.25得到1.5

<<

左移

把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即0和1)

2 << 2得到8。——2按比特表示为10

>>

右移

把一个数的比特向右移一定数目

11 >> 1得到5。——11按比特表示为1011,向右移动1比特后得到101,即十进制的5。

&

按位与

数的按位与

5 & 3得到1。

|

按位或

数的按位或

5 | 3得到7。

^

按位异或

数的按位异或

5 ^ 3得到6

~

按位翻转

x的按位翻转是-(x+1)

~5得到-6。

<

小于

返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。

5 < 3返回0(即False)而3 < 5返回1(即True)。比较可以被任意连接:3 < 5 < 7返回True。

>

大于

返回x是否大于y

5 > 3返回True。如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。

<=

小于等于

返回x是否小于等于y

x = 3; y = 6; x <= y返回True。

>=

大于等于

返回x是否大于等于y

x = 4; y = 3; x >= y返回True。

==

等于

比较对象是否相等

x = 2; y = 2; x == y返回True。x = ‘str’; y = ‘stR’; x == y返回False。x = ‘str’; y = ‘str’; x == y返回True。

!=

不等于

比较两个对象是否不相等

x = 2; y = 3; x != y返回True。

not

布尔“非”

如果x为True,返回False。如果x为False,它返回True。

x = True; not x返回False。

and

布尔“与”

如果x为False,x and y返回False,否则它返回y的计算值。

x = False; y = True; x and y,由于x是False,返回False。在这里,Python不会计算y,因为它知道这个表达式的值肯定是False(因为x是False)。这个现象称为短路计算。

or

布尔“或”

如果x是True,它返回True,否则它返回y的计算值。

x = True; y = False; x or y返回True。短路计算在这里也适用。

练习

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 1 >>> 1 + 1
 2 2
 3 >>> 1 + 1 * 2
 4 3
 5 >>> (1 + 1 ) * 2       
 6 4
 7 >>> 0/32
 8 0
 9 >>> 32/0
10 Traceback (most recent call last):
11   File "<stdin>", line 1, in <module>
12 ZeroDivisionError: integer division or modulo by zero
13 >>> 3*3
14 9
15 >>> 2**8
16 256
17 >>> 2**32
18 4294967296
19 >>> 2**64
20 18446744073709551616L
21 >>> 2**32/1024/1024
22 4096
23 >>> print "以上是32位系统的寻址空间"
24 以上是32位系统的寻址空间
25 >>> 2**64/1024/1024
26 17592186044416L
27 >>> print “虽然上面是64位系统的寻址空间,但是不一定就支持”
28   File "<stdin>", line 1
29     print “虽然上面是64位系统的寻址空间,但是不一定就支持”
30           ^
31 SyntaxError: invalid syntax
32 >>> 2**42 /1024/1024
33 4194304
34 >>> 10%2
35 0
36 >>> 10%3
37 1
38 >>> print "作用是看一个数能不能被整成,过滤奇偶数"
39 作用是看一个数能不能被整成,过滤奇偶数

View Code

 

大于 小于 左移右移 按位与 按位或

>>> 3>2
True
>>> 3<2
False
>>> 3>=2
True
>>> 3!=2
True
>>> print "数字变成2进制"
数字变成2进制
>>> 5<<2
20
>>> 5>>2
1
>>> 5 | 3
7
>>> 5 & 3
1

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

1 2 3 4  5  6  7  8
1 2 4 8 16 32 64 128
数组5转二进制 5=1+4
1 0 1   所以是5就是00000101
左移两位 5<<2
0 0 1 0 1 所以5<<2结果是20 即4+16=20
右移两位 5>>2
1          所以结果是1
按位与 5&3
5的二进制 101  3的二进制是110
1 0 1
1 1 0
得出结果 1 0 0 竖向看:1和1与是1,0和1与是0,1和0与是0,所以得出的结果是1
按位或 5|3
5的二进制 101  3的二进制是110
1 0 1
1 1 0
得出结果 1 1 1 竖向看:1和1或是1,0和1或是1,1和0或是1,所以得出的结果是1+2+4=7

 

 

七 基本数据类型

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 

比如数字来说:

  数字的方法都放在int类中,而数字是类的实例化。 如上图所示

 

1 整型

n1=4
n2=4
print(n1.__add__(n2))

a=18
print("the num 18 's bit is:",a.bit_length())

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

  1 class int(object):
  2     """
  3     int(x=0) -> integer
  4     int(x, base=10) -> integer
  5     
  6     Convert a number or string to an integer, or return 0 if no arguments
  7     are given.  If x is a number, return x.__int__().  For floating point
  8     numbers, this truncates towards zero.
  9     
 10     If x is not a number or if base is given, then x must be a string,
 11     bytes, or bytearray instance representing an integer literal in the
 12     given base.  The literal can be preceded by '+' or '-' and be surrounded
 13     by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 14     Base 0 means to interpret the base from the string as an integer literal.
 15     >>> int('0b100', base=0)
 16     4
 17     """
 18     def bit_length(self): # real signature unknown; restored from __doc__
 19         """ 计算给出数字的二进制最小位数
 20         int.bit_length() -> int
 21         
 22         Number of bits necessary to represent self in binary.
 23         >>> bin(37)
 24         '0b100101'
 25         >>> (37).bit_length()
 26         6
 27         """
 28         return 0
 29 
 30     def conjugate(self, *args, **kwargs): # real signature unknown
 31         """返回该复数的共轭复数"""
 32  """ Returns self, the complex conjugate of any int. """
 33     pass
 34 
 35 @classmethod # known case
 36 def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
 37     """
 38     int.from_bytes(bytes, byteorder, *, signed=False) -> int
 39     
 40     Return the integer represented by the given array of bytes.
 41     
 42     The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
 43     
 44     The byteorder argument determines the byte order used to represent the
 45     integer.  If byteorder is 'big', the most significant byte is at the
 46     beginning of the byte array.  If byteorder is 'little', the most
 47     significant byte is at the end of the byte array.  To request the native
 48     byte order of the host system, use `sys.byteorder' as the byte order value.
 49     
 50     The signed keyword-only argument indicates whether two's complement is
 51     used to represent the integer.
 52     """
 53     pass
 54 
 55 def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
 56     """
 57     int.to_bytes(length, byteorder, *, signed=False) -> bytes
 58     
 59     Return an array of bytes representing an integer.
 60     
 61     The integer is represented using length bytes.  An OverflowError is
 62     raised if the integer is not representable with the given number of
 63     bytes.
 64     
 65     The byteorder argument determines the byte order used to represent the
 66     integer.  If byteorder is 'big', the most significant byte is at the
 67     beginning of the byte array.  If byteorder is 'little', the most
 68     significant byte is at the end of the byte array.  To request the native
 69     byte order of the host system, use `sys.byteorder' as the byte order value.
 70     
 71     The signed keyword-only argument determines whether two's complement is
 72     used to represent the integer.  If signed is False and a negative integer
 73     is given, an OverflowError is raised.
 74     """
 75     pass
 76 
 77 def __abs__(self, *args, **kwargs): # real signature unknown
 78 """ 返回绝对值 """
 79 
 80     """ abs(self) """
 81     pass
 82 
 83 def __add__(self, *args, **kwargs): # real signature unknown
 84     """ Return self+value. """
 85     pass
 86 
 87 def __and__(self, *args, **kwargs): # real signature unknown
 88     """ Return self&value. """
 89     pass
 90 
 91 def __bool__(self, *args, **kwargs): # real signature unknown
 92     """ self != 0 """
 93     pass
 94 
 95 def __ceil__(self, *args, **kwargs): # real signature unknown
 96     """ Ceiling of an Integral returns itself. """
 97     pass
 98 
 99 def __divmod__(self, *args, **kwargs): # real signature unknown
100     """
101 相除,得到商和余数组成的元组
102 Return divmod(self, value). """
103     pass
104 
105 def __eq__(self, *args, **kwargs): # real signature unknown
106     """ Return self==value. """
107     pass
108 
109 def __float__(self, *args, **kwargs): # real signature unknown
110     """
111 转换为浮点类型
112 float(self) """
113     pass
114 
115 def __floordiv__(self, *args, **kwargs): # real signature unknown
116     """ Return self//value. """
117     pass
118 
119 def __floor__(self, *args, **kwargs): # real signature unknown
120     """ Flooring an Integral returns itself. """
121     pass
122 
123 def __format__(self, *args, **kwargs): # real signature unknown
124     pass
125 
126 def __getattribute__(self, *args, **kwargs): # real signature unknown
127     """ Return getattr(self, name). """
128     pass
129 
130 def __getnewargs__(self, *args, **kwargs): # real signature unknown
131     pass
132 
133 def __ge__(self, *args, **kwargs): # real signature unknown
134     """ Return self>=value. """
135     pass
136 
137 def __gt__(self, *args, **kwargs): # real signature unknown
138     """ Return self>value. """
139     pass
140 
141 def __hash__(self, *args, **kwargs): # real signature unknown
142     """ Return hash(self). """
143     pass
144 
145 def __index__(self, *args, **kwargs): # real signature unknown
146     """ Return self converted to an integer, if self is suitable for use as an index into a list. """
147     pass
148 
149 def __init__(self, x, base=10): # known special case of int.__init__
150     """
151     int(x=0) -> integer
152     int(x, base=10) -> integer
153     
154     Convert a number or string to an integer, or return 0 if no arguments
155     are given.  If x is a number, return x.__int__().  For floating point
156     numbers, this truncates towards zero.
157     
158     If x is not a number or if base is given, then x must be a string,
159     bytes, or bytearray instance representing an integer literal in the
160     given base.  The literal can be preceded by '+' or '-' and be surrounded
161     by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
162     Base 0 means to interpret the base from the string as an integer literal.
163     >>> int('0b100', base=0)
164     4
165     # (copied from class doc)
166     """
167     pass
168 
169 def __int__(self, *args, **kwargs): # real signature unknown
170     """ int(self) """
171     pass
172 
173 def __invert__(self, *args, **kwargs): # real signature unknown
174     """ ~self """
175     pass
176 
177 def __le__(self, *args, **kwargs): # real signature unknown
178     """ Return self<=value. """
179     pass
180 
181 def __lshift__(self, *args, **kwargs): # real signature unknown
182     """ Return self<<value. """
183     pass
184 
185 def __lt__(self, *args, **kwargs): # real signature unknown
186     """ Return self<value. """
187     pass
188 
189 def __mod__(self, *args, **kwargs): # real signature unknown
190     """ Return self%value. """
191     pass
192 
193 def __mul__(self, *args, **kwargs): # real signature unknown
194     """ Return self*value. """
195     pass
196 
197 def __neg__(self, *args, **kwargs): # real signature unknown
198     """ -self """
199     pass
200 
201 @staticmethod # known case of __new__
202 def __new__(*args, **kwargs): # real signature unknown
203     """ Create and return a new object.  See help(type) for accurate signature. """
204     pass
205 
206 def __ne__(self, *args, **kwargs): # real signature unknown
207     """ Return self!=value. """
208     pass
209 
210 def __or__(self, *args, **kwargs): # real signature unknown
211     """ Return self|value. """
212     pass
213 
214 def __pos__(self, *args, **kwargs): # real signature unknown
215     """ +self """
216     pass
217 
218 def __pow__(self, *args, **kwargs): # real signature unknown
219     """ Return pow(self, value, mod). """
220     pass
221 
222 def __radd__(self, *args, **kwargs): # real signature unknown
223     """ Return value+self. """
224     pass
225 
226 def __rand__(self, *args, **kwargs): # real signature unknown
227     """ Return value&self. """
228     pass
229 
230 def __rdivmod__(self, *args, **kwargs): # real signature unknown
231     """ Return divmod(value, self). """
232     pass
233 
234 def __repr__(self, *args, **kwargs): # real signature unknown
235     """ Return repr(self). """
236     pass
237 
238 def __rfloordiv__(self, *args, **kwargs): # real signature unknown
239     """ Return value//self. """
240     pass
241 
242 def __rlshift__(self, *args, **kwargs): # real signature unknown
243     """ Return value<<self. """
244     pass
245 
246 def __rmod__(self, *args, **kwargs): # real signature unknown
247     """ Return value%self. """
248     pass
249 
250 def __rmul__(self, *args, **kwargs): # real signature unknown
251     """ Return value*self. """
252     pass
253 
254 def __ror__(self, *args, **kwargs): # real signature unknown
255     """ Return value|self. """
256     pass
257 
258 def __round__(self, *args, **kwargs): # real signature unknown
259     """
260     Rounding an Integral returns itself.
261     Rounding with an ndigits argument also returns an integer.
262     """
263     pass
264 
265 def __rpow__(self, *args, **kwargs): # real signature unknown
266     """ Return pow(value, self, mod). """
267     pass
268 
269 def __rrshift__(self, *args, **kwargs): # real signature unknown
270     """ Return value>>self. """
271     pass
272 
273 def __rshift__(self, *args, **kwargs): # real signature unknown
274     """ Return self>>value. """
275     pass
276 
277 def __rsub__(self, *args, **kwargs): # real signature unknown
278     """ Return value-self. """
279     pass
280 
281 def __rtruediv__(self, *args, **kwargs): # real signature unknown
282     """ Return value/self. """
283     pass
284 
285 def __rxor__(self, *args, **kwargs): # real signature unknown
286     """ Return value^self. """
287     pass
288 
289 def __sizeof__(self, *args, **kwargs): # real signature unknown
290     """ Returns size in memory, in bytes """
291     pass
292 
293 def __str__(self, *args, **kwargs): # real signature unknown
294     """ Return str(self). """
295     pass
296 
297 def __sub__(self, *args, **kwargs): # real signature unknown
298     """ Return self-value. """
299     pass
300 
301 def __truediv__(self, *args, **kwargs): # real signature unknown
302     """ Return self/value. """
303     pass
304 
305 def __trunc__(self, *args, **kwargs): # real signature unknown
306     """ Truncating an Integral returns itself. """
307     pass
308 
309 def __xor__(self, *args, **kwargs): # real signature unknown
310     """ Return self^value. """
311     pass
312 
313 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
314 """the denominator of a rational number in lowest terms"""
315 
316 imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
317 """the imaginary part of a complex number"""
318 
319 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
320 """the numerator of a rational number in lowest terms"""
321 
322 real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
323 """the real part of a complex number"""

View Code

 

2、布尔值   真或假   1 或 0
3、字符串

"hello world"

万恶的字符串拼接:   python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。 字符串格式化

name = "alex"
print "i am %s " % name
  
#输出: i am alex

PS: 字符串是 %s;整数 %d;浮点数%f

字符串常用功能:  
后面有练习

  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

class str(object):
    """
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
    
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.
    """
    def capitalize(self): # real signature unknown; restored from __doc__
        """ #将 字符串首字母 小写改大写
        S.capitalize() -> str
        
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.

        """
        return ""

    def casefold(self): # real signature unknown; restored from __doc__
        """
        S.casefold() -> str
        
        Return a version of S suitable for caseless comparisons.
        """
        return ""

    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """ 可以为字符串 填充自定字符 长度=字符+指定字符
        S.center(width[, fillchar]) -> str
        
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """  下面是详细参数: 
        子串:是要搜索的子串。

        开始:从该指数开始搜索。第一个字符从索引0开始。通过默认搜索引擎从索引0开始。

        结束:搜索从该指数结束。第一个字符从索引0开始。默认情况下,搜索结束,在最后一个索引。


        S.count(sub[, start[, end]]) -> int
        
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """ 编码 上面有介绍
        S.encode(encoding='utf-8', errors='strict') -> bytes
        
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

    def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """  以 某个字符结束
          suffix -- 该参数可以是一个字符串或者是一个元素。

      start -- 字符串中的开始位置。

      end -- 字符中结束位置。

 

      返回值

 

      如果字符串含有指定的后缀返回True,否则返回False。



        S.endswith(suffix[, start[, end]]) -> bool
        
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """ 把tab转换成空格
        S.expandtabs(tabsize=8) -> str
        
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
find(str, pos_start, pos_end)

解释:

  str:被查找“字串”

  pos_start:查找的首字母位置(从0开始计数。默认:0)

  pos_end: 查找的末尾位置(默认-1)

返回值:如果查到:返回查找的第一个出现的位置。否则,返回-1。



        S.find(sub[, start[, end]]) -> int
        
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

    def format(*args, **kwargs): # known special case of str.format
        """  占位符  类似变量引用
      s = "print hell {0} ,age {1}"
      print(s.format('alex',19))


        S.format(*args, **kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def format_map(self, mapping): # real signature unknown; restored from __doc__
        """字符串格式化,动态参数,将函数式编程时细说
        S.format_map(mapping) -> str
        
        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""

    def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """ #跟find类似但是 没有找到的话会报错。 而find是返回-1
        S.index(sub[, start[, end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self): # real signature unknown; restored from __doc__
        """ #判断是否是数字和字母
        S.isalnum() -> bool
        
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self): # real signature unknown; restored from __doc__
        """是否是字母 
        S.isalpha() -> bool
        
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool
        
        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False

    def isdigit(self): # real signature unknown; restored from __doc__
        """ 是否是数字
        S.isdigit() -> bool
        
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool
        
        Return True if S is a valid identifier according
        to the language definition.
        
        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False

    def islower(self): # real signature unknown; restored from __doc__
        """是否小写字母
        S.islower() -> bool
        
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool
        
        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False

    def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool
        
        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False

    def isspace(self): # real signature unknown; restored from __doc__
        """是否是空格
        S.isspace() -> bool
        
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self): # real signature unknown; restored from __doc__
        """ 是否是标题  字符串开头是大写 后面是小写
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False

    def isupper(self): # real signature unknown; restored from __doc__
        """ 是否是大写
        S.isupper() -> bool
        
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def join(self, iterable): # real signature unknown; restored from __doc__
        """ 拼接 后面有例子

        S.join(iterable) -> str
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

    def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """ 内容左对齐,右侧填充
    ljust()方法语法:

 

    str.ljust(width[, fillchar])

 

    参数

 

    width -- 指定字符串长度。

    fillchar -- 填充字符,默认为空格。

 

    返回值

 

    返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

 S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ 转换为小写 S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ 去除左侧开头空白 S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def maketrans(self, *args, **kwargs): # real signature unknown """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ pass def partition(self, sep): # real signature unknown; restored from __doc__ """ 以指定 字符 开始分割 指定的字符也显示 S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ 替换
    old -- 将被替换的子字符串。

    new -- 新字符串,用于替换old子字符串。

    max -- 可选字符串, 替换不超过 max 次

    返回值

    返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。



        S.replace(old, new[, count]) -> str
        
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """ 从右开始查找
        S.rfind(sub[, start[, end]]) -> int
        
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

    def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """ 顾名思义从右侧匹配
        S.rindex(sub[, start[, end]]) -> int
        
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

    def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """ 从右侧 填充
        S.rjust(width[, fillchar]) -> str
        
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def rpartition(self, sep): # real signature unknown; restored from __doc__
        """ 从右侧开始找到 分割 分割字符也显示
        S.rpartition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """ 从右侧开始分割 sep是指定几个
        S.rsplit(sep=None, maxsplit=-1) -> list of strings
        
        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """ 从右侧 去除结尾的空格
        S.rstrip([chars]) -> str
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """ 分割 sep是几个算分割符
        S.split(sep=None, maxsplit=-1) -> list of strings
        
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []

    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings
        
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """ 指定以什么开始
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """  去除两端空格
        S.strip([chars]) -> str
        
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

    def swapcase(self): # real signature unknown; restored from __doc__
        """ 大写转小写小写转大写
        S.swapcase() -> str
        
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""

    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
        
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""

    def translate(self, table): # real signature unknown; restored from __doc__
        """


    转换,需要先做一个对应表,最后一个表示删除字符集合
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab)
    str = "this is string example....wow!!!"print str.translate(trantab, 'xm')




        S.translate(table) -> str
        
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""

    def upper(self): # real signature unknown; restored from __doc__
        """ 大写显示
        S.upper() -> str
        
        Return a copy of S converted to uppercase.
        """
        return ""

    def zfill(self, width): # real signature unknown; restored from __doc__
        """ 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
        S.zfill(width) -> str
        
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

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

    def __format__(self, format_spec): # real signature unknown; restored from __doc__
        """
        S.__format__(format_spec) -> str
        
        Return a formatted version of S as described by format_spec.
        """
        return ""

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

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

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        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 __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
        """
        str(object='') -> str
        str(bytes_or_buffer[, encoding[, errors]]) -> str
        
        Create a new string object from the given object. If encoding or
        errors is specified, then the object must expose a data buffer
        that will be decoded using the given encoding and error handler.
        Otherwise, returns the result of object.__str__() (if defined)
        or repr(object).
        encoding defaults to sys.getdefaultencoding().
        errors defaults to 'strict'.
        # (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 __mod__(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 __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self. """
        pass

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

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

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

View Code

 

 示例
 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'


a1 = "Alex"
print(a1.capitalize())

b="alex alex alex"
print(b.center(20,"*"))

print(b.count("le",1,9))
print(b.find("xxlex"))
print(b.istitle())
print(b.partition("le"))
print(b.replace("ale","ALE",2))
print(b.split("le",2))
print(a1.swapcase())
print(a1.upper())
print(a1.zfill(20))
print(a1.__add__("dfsf"))
s = " hell {0} ,age {1}"
print(s.format('alex',19))
print("字符串的分片",a1[0],a1[0:2],a1[0:])


注意: strip()
  1 可以去除两端空格
2 可以去除末尾\n
3 可以去除 空行
4 可以传如参数,比如
    n = “hello”
s = n.strip(“o”)
    print s 结果是 = ‘hell’

 

4、列表 创建列表:

 

name_list = ['alex', 'seven', 'eric']
或
name_list = list(['alex', 'seven', 'eric'])

基本操作:

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 包含

 

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

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__
        """ 浅copy  L.copy() -> list -- a shallow copy of L """
        return []

    def count(self, value): # real signature unknown; restored from __doc__
        """ 匹配 value的个数   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__
        """ 返回 某个value 的索引
        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__
        """ 排序 但是int str不行  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

View Code

示例:

###### 列表 ##########

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'


lis=[1,2,3,'alex']
cc=[5,5]
print(lis.count("alex"))
lis.extend(cc)
print(lis)

name_list = ["eirc", "alex", 'tony']
"""
# 索引
print(name_list[0])
# 切片
print(name_list[0:2])
# len
print(name_list[2:len(name_list)])
# for
for i in name_list:
    print(i)


#join 方法,拼接字符串
li = ["alex","eric"]
name = "li jie"
ss = "_".join(li)
s = "_".join(name)
print(s,ss)


"""
# 列表内部提供的其他功能
# append后追加
name_list.append('seven')
name_list.append('seven')
name_list.append('seven')
print(name_list)
# 元素出现的次数
print(name_list.count('seven'))
# iterable,可迭代的
temp = [111,22,33,44]
# 扩展,批量添加
name_list.extend(temp)
print(name_list)
# 获取指定元素的索引位置
print(name_list.index('alex'))
# 向指定索引位置插入数据
name_list.insert(1, 'SB')
print(name_list)
# 在原列表中移除掉最后一个元素,并将其赋值给 a1
a1 = name_list.pop()
print(name_list)
print(a1)
# 移除某个元素
name_list.remove('seven')
print(name_list)
# 翻转
name_list.reverse()
print(name_list)

# 删除指定索引位置
print(name_list)
del name_list[1:3]
print(name_list)

列表练习

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

  1 列表表示:key  下表  列表
  2 root@python:~# python
  3 Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
  4 [GCC 4.8.2] on linux2
  5 Type "help", "copyright", "credits" or "license" for more information.
  6 列表创建 
  7 >>> names = ['IBM','Blue Polo','TieZhuang','DaShuai']
  8 查看列表的值    数字是列表元素的下标
  9 >>> names[0]
 10 'IBM'
 11 >>> names[1]
 12 'Blue Polo'
 13 >>> names[2]
 14 'TieZhuang'
 15 看最后一个值
 16 >>> names[-1] 
 17 'DaShuai'
 18 
 19 列表的元素位置取值
 20 聚合另一个列表
 21 >>> names.extend(range(1000))   #range(1000)是创建1000个数字的列表,extend是聚合names原来的列表追加上1000个数字
 22 >>> names  #看全部的值
 23 
 24 
 25 取前十个值
 26 >>> names[0:9]
 27 ['IBM', 'Blue Polo', 'TieZhuang', 'DaShuai', 0, 1, 2, 3, 4]
 28 取后五个值
 29 >>> names[-5:-1]   #不对
 30 [995, 996, 997, 998]
 31 
 32 >>> names[-5:]    #正确的写法
 33 [995, 996, 997, 998, 999]
 34 
 35 Names的内置函数讲解
 36 
 37 Names.append() 追加列表的值
 38 >>> names.append(559)     #末尾追加559
 39 >>> names[-3:]       #查看后三位
 40 [998, 999, 559]
 41 
 42 Names.index() 查看列表该值所在的索引位置
 43 >>> names.index(559)   #查看559 所在的索引位置
 44 563
 45 >>> names.insert(500,'IBM')
 46 >>> names[500]
 47 'IBM'
 48 
 49 找到列表值为559 
 50 再添加一个559
 51 >>> names.append(559) 
 52 看一下有没有
 53 >>> names[-3:]
 54 [998, 999, 559]
 55 看一下索引
 56 >>> names.index(559) 
 57 563
 58 取到值559
 59 >>> names[names.index(559)]
 60 559
 61 names.count()查看列表值的个数
 62 
 63 >>> names[-3:]
 64 [999, 559, 'liujianzuo']
 65 >>> names.count(559)
 66 2
 67 >>> names.count('IBM')     
 68 2
 69 Names.insert()指定位置插入值
 70 >>> names.insert(600,'IBM')
 71 >>> names.insert(650,'IBM')
 72 >>> names.count('IBM')     
 73 4
 74 names[$index] = ‘key’改列表中某个值为另一个值
 75 >>> names.index('IBM')
 76 0
 77 >>> names[names.index('IBM')]
 78 'IBM'
 79 >>> names[names.index('IBM')] = 'IBm'
 80 >>> names.index('IBm')
 81 0
 82 >>> names[0]
 83 'IBm'
 84 再次查看 下一个IBM索引变道500了
 85 >>> names[names.index('IBM')]
 86 'IBM'
 87 >>> names.index('IBM')       
 88 500
 89 
 90 练习:批量替换 列表中的IBM 为HP
 91 root@python:/home/liujianzuo/py_training/seminar6/day2# cat liebiao.py 
 92 #!/usr/bin/env python
 93 names = ['IBM','alex','liujianzuo','ddd']
 94 #names = []
 95 names.extend(range(1000))
 96 #naems = names + range(1000)
 97 names.insert(100,'IBM')
 98 names.insert(200,'IBM')
 99 names.insert(300,'IBM')
100 
101 
102 for i in range(names.count('IBM')):
103   ibm_index = names.index('IBM')
104   print " IBM's INDEX :" ,  ibm_index 
105   names[ibm_index] = 'HP'
106 print "HP's count num is :" ,names.count('HP')
107 
108 三个注意 :批量替换 列表中的IBM 为HP:
109 1、print格式
110 print  “输出描述内容”  逗号   变量
111 Print 变量值输出来,如果我要把描述内容放在变量前面,一定要记得加逗号,不然会报错
112 root@python:/home/liujianzuo/py_training/seminar6/day2# python liebiao.py 
113   File "liebiao.py", line 15
114     print "HP's count num is :" names.count('HP')
115 
116 2、如果要赋值一个空列表
117    #names = []
118 3、聚合两个列表的另一种方法
119 #naems = names + range(1000)
120 names.extend(range(1000))
121 
122 A.pop() a.remove() a.reverse()
123 root@python:~# python
124 Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
125 [GCC 4.8.2] on linux2
126 Type "help", "copyright", "credits" or "license" for more information.
127 赋值一个列表
128 >>> a = range(100)
129 >>> a
130 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
131 A.pop()删除最后一个元素
132 >>> a.pop()
133 99
134 >>> a
135 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
136 a.remove(23) 移除列表内容
137 >>> import tab
138 >>> a.remove(23)
139 >>> a
140 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
141 测试remove
142 >>> a.insert(23,'IBM')
143 >>> a.remove(23)
144 Traceback (most recent call last):
145   File "<stdin>", line 1, in <module>
146 ValueError: list.remove(x): x not in list
147 >>> a.index('IBM'
148 ... 
149 KeyboardInterrupt
150 >>> a.index('IBM')
151 23
152 >>> a.remove('IBM')   
153 >>> a
154 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
155 a.reverse() 反转列表元素
156 >>> a.reverse()
157 >>> a
158 [98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
159 A.sort()排序列表
160 数字 大写字母 小写字母
161 >>> a.insert(3,5)
162 >>> a
163 [98, 97, 96, 5, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
164 >>> a.sort()
165 >>> a
166 [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
167 >>> a.insert(5,'a') 
168 >>> a.insert(5,'A')
169 >>> a.insert(5,'B')
170 >>> a.insert(5,'b')
171 >>> a
172 [0, 1, 2, 3, 4, 'b', 'B', 'A', 'a', 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
173 >>> a.sort()
174 >>> a
175 [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 'A', 'B', 'a', 'b']
176 >>> a.insert(11,'~')
177 >>> a.insert(11,'!')
178 >>> a.insert(11,'#')
179 >>> a.insert(11,'@')
180 >>> a
181 [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, '@', '#', '!', '~', 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 'A', 'B', 'a', 'b']
182 >>> a.sort()
183 >>> a
184 [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, '!', '#', '@', 'A', 'B', 'a', 'b', '~']
185 String方法 
186 >>> import string
187 >>> string.ascii_letters
188 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
189 >>> string.ascii_
190 string.ascii_letters    string.ascii_uppercase
191 string.ascii_lowercase  
192 >>> string.ascii_lowercase
193 'abcdefghijklmnopqrstuvwxyz'
194 >>> a = string.ascii_lowercase
195 >>> a
196 'abcdefghijklmnopqrstuvwxyz'
197 list(a)将连续的列表做成字符列表
198 >>> list(a
199 a       all(    any(    as      
200 abs(    and     apply(  assert  
201 >>> list(a)
202 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
203 >>> a.split()
204 ['abcdefghijklmnopqrstuvwxyz']
205 >>> a
206 'abcdefghijklmnopqrstuvwxyz'
207 >>> str(a)
208 'abcdefghijklmnopqrstuvwxyz'
209 >>> a
210 'abcdefghijklmnopqrstuvwxyz'
211 Join方法将分散的多个元素组成一个元素的列表
212 '|'.join(a) 以竖划线为分隔符作为a列表的分割元素分割
213 >>> a = list(string.ascii_lowercase)
214 >>> a
215 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
216 >>> type(a
217 a       all(    any(    as      
218 abs(    and     apply(  assert  
219 >>> type(a)
220 <type 'list'>
221 >>> str(a)
222 "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']"
223 >>> 
224 >>> str(a)
225 "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']"
226 >>> a[0]
227 'a'
228 >>> a[1]
229 'b'
230 >>> ''.join(a)
231 'abcdefghijklmnopqrstuvwxyz'
232 >>> '_'.join(a)
233 'a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z'
234 >>> '|'.join(a)
235 'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z'
236 >>> a[1]       
237 'b'
238 
239 Str()的用法  例如file是只能写入字符串的我想写入数字
240 >>> type(4)
241 <type 'int'>
242 >>> type(str(4))
243 <type 'str'>
244 将数组写入文件f.readlines(数组)
245 
246 >>> f = open('test2.txt','w')
247 >>> f.write(5)
248 Traceback (most recent call last):
249   File "<stdin>", line 1, in <module>
250 TypeError: expected a character buffer object
251 >>> a
252 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
253 >>> f.writelines(a)
254 >>> f.close()
255 root@python:~# cat test2.txt 
256 abcdefghijklmnopqrstuvwxyz
257 
258 
259 程序在写文件的时候还没保存,另一个程序要调用用一个文件如何办
260 例如:
261 你在vi一个文件的时候,你用python的file方法写了数据到该文件。你vi这个文件无法保存。
262 Python写文件系统内核不会给你加锁,而vi枷锁了,例如vi产生一个swp文件
263 Python没加 靠自己判断了。
264 Python判断文件打开了???
265 
266 With opne(file) as 别名 不用关闭文件,with语法结束之后文件就关闭。 解决长时间运行程序的方法
267 打开文件不要忘记关闭它不要让程序去关闭它,尤其是运行好些天的程序,程序打开了高些文件后,运行几天后,这个程序的cpu就百分之百了。会维护者好几个文件打开者的句柄
268 
269 
270 >>> with open ('test2.txt','r') as f:
271 ...   for i in f.readlines():        
272 ...     print i              
273 ... 
274 Abcdefghijklmnopqrstuvwxyz
275 
276 >>> with open ('test2.txt','a') as f: 
277 ...   f.write('\n+++++')
278 ... 
279 
280 Del 删除内存的东西 删除列表的指定内容元素
281 >>> a=range(40)
282 >>> a
283 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
284 >>> 
285 
286 >>> del a[6:11]
287 >>> a
288 [0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
289 >>> b=a[7:20]
290 >>> b
291 [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
292 >>> del b
293 >>> b
294 Traceback (most recent call last):
295   File "<stdin>", line 1, in <module>
296 NameError: name 'b' is not defined

View Code

 

  

 

5、元组
创建元祖: 元组一旦创建 不等增加也不能减少

 ages = (11, 22, 33, 44, 55) 或 ages = tuple((11, 22, 33, 44, 55)) 

基本操作:
索引
切片
循环
长度
包含

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items
    
    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """  计算 value的个数  T.count(value) -> integer -- return number of occurrences of value """
        return 0

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

    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 __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, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        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 __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, seq=()): # known special case of tuple.__init__
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items
        
        If the argument is a tuple, the return value is the same object.
        # (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 __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

View Code

 

示例:

############### 元组 #################
name_tuple = ('alex', 'eric')
# 索引
print(name_tuple[0])
# len
print(name_tuple[len(name_tuple)-1])
# 切片
print(name_tuple[0:1])
# for
for i in name_tuple:
    print(i)
# 删除
# del name_tuple[0] 不支持
# count,计算元素出现的个数
print(name_tuple.count('alex'))
# index 获取指定元素的索引位置
print(name_tuple.index('alex'))

元组练习

不想别人改  默认变量 等。 别人调用你的程序元组。别人该你的不想改 用元组
只有两个方法
 c.count(
  c.index(

tuple(列表)列表变元组
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d=tuple(a)
>>> d
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
list(元组)元组变列表
>>> d
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> e = list(a)
>>> e
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

 
6、字典(无序) 创建字典:

person = {"name": "mr.wu", 'age': 18}
或
person = dict({"name": "mr.wu", 'age': 18})

常用操作:

  • 索引
  • 新增
  • 删除
  • 键、值、键值对
  • 循环
  • 长度

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    def clear(self): # real signature unknown; restored from __doc__
        """ 清除 字典  D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """  浅拷贝  D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根据key获取 d是默认是 为 None   D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def items(self): # real signature unknown; restored from __doc__
        """ 将字典的key value都打印成列表元组   D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """打印字典的key   D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """ 获取并在列表中移除
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """如果key不存在,则创建,如果存在,则返回已存在的值且不修改

   D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ 所有的值  D.values() -> an object providing a view on D's values """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ True if D has a key k, else False. """
        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 __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (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

    @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 __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

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

    __hash__ = None

View Code

 

 

示例: 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'


dic={1:2,"alex":4,4:9}
print(dic.get("alex"))
print(dic.items())
print(dic.keys())
print(dic.values())
print(dic.pop(2,None))
print(dic.setdefault("name","rain"))

#
##################### 字典 ################### # 字典的每一个元素,键值对 user_info = { 0: "alex", "age": 73, 2: 'M' } # 0 “alex" # 1 73 # 索引 # print(user_info[0]) # print(user_info["age"]) # 循环,默认值输出key # for i in user_info: # print(i) # # 获取所有键 # print(user_info.keys()) # # 获取所有值 # print(user_info.values()) # # 获取所有键值对 # print(user_info.items()) # for i in user_info.keys(): # print(i) # # for i in user_info.values(): # print(i) # user_info = { # 0: "alex", # "age": 73, # 2: 'M' # } # for k,v in user_info.items(): # print(k) # print(v) # clear,清除所有内容 # user_info.clear() # print(user_info) # get 根据key获取值,如果key不存在,可以指定一个默认值 # val = user_info.get('age') # print(val) # val = user_info.get('age', '123') # print(val) # 索引取值时,key不存在,报错 # print(user_info['age']) # print(user_info['age1111']) # has_key 检查字典中指定key是否存在 3版本python没有了 可以用in 判断 # ret = 'agfffe' in user_info.keys() # print(ret) # pop # popitem # update # print(user_info) # test = { # "a1": 123, # 'a2': 456 # } # user_info.update(test) # print(user_info) # 删除指定索引的键值对 test = { "a1": 123, 'a2': 456 } del test['a1'] print(test)

PS:循环,range,continue 和 break

字典练习

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 1 value末尾不要忘记加逗号
 2 contact = {
 3     '222' : ['dfas','fdas','hjgkj'],
 4     'gkgj' : ['dsfa','dsfa'],
 5     '3333' : ['dsfa','dsfa'],   
 6     '324234' : ['dsaf','fdasfsa']
 7 }
 8 
 9 print contact['222']  #打印字典的key为222的value
10 contact['222'][2] = '12314'  #将该key的第二个value改为12314
11 print contact['222']  #打印字典的key为222的value
12 
13 执行结果
14 C:\Python27\python.exe //192.168.92.131/Share/py_training/seminar6/day2/dict.py
15 ['dfas', 'fdas', 'hjgkj']
16 ['dfas', 'fdas', '12314']
17 
18 
19 contact = {                      
20     '222' : ['alex','it','num'], 
21     '3333' : ['dsfa','dsfa'],   
22     '324234' : ['dsaf','fdasfsa']
23 }
24 字典的内置函数
25 >>> contact = {                      
26 ...     '222' : ['alex','it','num'], 
27 ...     '3333' : ['dsfa','dsfa'],   
28 ...     '324234' : ['dsaf','fdasfsa']
29 ... }
30 >>> import tab
31 >>> contact.
32 contact.clear(
33 contact.copy(
34 contact.fromkeys(
35 contact.get(
36 contact.has_key(
37 contact.items(
38 contact.iteritems(
39 contact.iterkeys(
40 contact.itervalues(
41 contact.keys(
42 contact.pop(
43 contact.popitem(
44 contact.setdefault(
45 contact.update(
46 contact.values(
47 contact.viewitems(
48 contact.viewkeys(
49 contact.viewvalues(

View Code

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》
《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

  1 2版本python 查看字典有没有这个key
  2 >>> contact['4343']
  3 Traceback (most recent call last):
  4   File "<stdin>", line 1, in <module>
  5 KeyError: '4343'
  6 >>> contact.has_key('343')
  7 False
  8 >>> contact.has_key('3333')
  9 True
 10 清空字典contact.clear()
 11 >>> contact.clear()
 12 
 13 字典做列表contact.items()
 14 >>> contact.items()
 15 [('3333', ['dsfa', 'dsfa']), ('222', ['alex', 'it', 'num']), ('324234', ['dsaf', 'fdasfsa'])]
 16 实验操作 一个参数只打印key
 17 contact = {
 18     '222' : ['alex','it','num'],
 19     '3333' : ['dsfa','dsfa'],
 20     '324234' : ['dsaf','fdasfsa']
 21 }
 22 
 23 for i in contact:
 24     print  i,contact[i]
 25 C:\Python27\python.exe //192.168.92.131/Share/py_training/seminar6/day2/dict.py
 26 3333 ['dsfa', 'dsfa']
 27 222 ['alex', 'it', 'num']
 28 324234 ['dsaf', 'fdasfsa']
 29 
 30 contact.items()  Key和value都打印
 31 contact = {
 32     '222' : ['alex','it','num'],
 33     '3333' : ['dsfa','dsfa'],
 34     '324234' : ['dsaf','fdasfsa']
 35 }
 36 for k,v in contact.items():
 37 print k,v
 38 C:\Python27\python.exe //192.168.92.131/Share/py_training/seminar6/day2/dict.py
 39 3333 ['dsfa', 'dsfa']
 40 222 ['alex', 'it', 'num']
 41 324234 ['dsaf', 'fdasfsa']
 42 注意
 43 Contact.item()会把一个字典转换成列表,但是大数据的话,会花费一定时间的,那种情况下就会慢,特别大的数据不建议循环。如果非要在大数据循环用如下办法:
 44 for i in contact:
 45     print  i,contact[i]
 46 几万条数据没关系
 47 
 48 
 49 字典增加、修改数据
 50 a.get('key')  来确定这个key是否存在而不报错
 51 >>> a = {'name':'alex','age':'29'}
 52 >>> a['sex']
 53 Traceback (most recent call last):
 54   File "<stdin>", line 1, in <module>
 55 KeyError: 'sex'
 56 >>> b=a.get('sex')   #字典没有sex
 57 >>> b
 58 >>> print b    #查看为None
 59 None
 60 >>> b=a.get('name')
 61 >>> b
 62 'alex'
 63 >>> print b
 64 alex
 65 > a.iteritems() 迭代器介绍 后面介绍
 66 >>> a.iteritems()
 67 <dictionary-itemiterator object at 0x7ff61e25b680>
 68 >>> print '这是一个迭代器 加速搜索过程'
 69 这是一个迭代器 加速搜索过程
 70 > a.keys()显示字典的key
 71 >>> a.keys()
 72 ['age', 'name']
 73 > a.values()显示字典value
 74 >>> a.values()
 75 ['29', 'alex']
 76 a.pop() 删除key
 77 >>> a.pop()
 78 Traceback (most recent call last):
 79   File "<stdin>", line 1, in <module>
 80 TypeError: pop expected at least 1 arguments, got 0
 81 >>> a.pop('age')
 82 '29'
 83 >>> a
 84 {'name': 'alex'}
 85 > a['age']=29   > a['sex']='Feale'  增加更改字典的内容
 86 >>> a['age']=29
 87 >>> a['sex']='Male'
 88 >>> a
 89 {'age': 29, 'name': 'alex', 'sex': 'Male'}
 90 >>> a['sex']='Feale'
 91 >>> a
 92 {'age': 29, 'name': 'alex', 'sex': 'Feale'}
 93 字典是无序的
 94 
 95 >>> a['birthday']=0624
 96 >>> a
 97 {'age': 29, 'birthday': 404, 'name': 'alex', 'sex': 'Feale'}
 98 >>> a['country']='CN'
 99 >>> a
100 {'country': 'CN', 'age': 29, 'birthday': 404, 'name': 'alex', 'sex': 'Feale'}
101 >>> print '字典是无序的'
102 字典是无序的
103 a.popitem()也是无序删除的
104 >>> a.popitem()
105 ('country', 'CN')
106 >>> a.popitem()
107 ('age', 29)
108 >>> a.popitem()
109 ('birthday', 404)
110 注意 a.popitem()也是无序删除的
111 
112 >a.setdefault保护字典的数据
113 >>> a.setdefault('Occupation')
114 >>> a
115 {'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Occupation': None}
116 >>> a.setdefault('Occupation','IT')
117 >>> a
118 {'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Occupation': None}
119 >>> a.setdefault('Height','170')
120 '170'
121 >>> a
122 {'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
123 >>> a.setdefault('Height','190')
124 '170'
125 >>> a
126 {'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
127 >>>
128 
129 聚合字典a.update()
130 
131 >>> a.update()
132 >>> a
133 {'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
134 >>> b={1:2,2:3,3:4}
135 >>> a.update(b)
136 >>> a
137 {1: 2, 2: 3, 3: 4, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
138 >>> b={1:2,2:3,3:66}
139 >>> b
140 {1: 2, 2: 3, 3: 66}
141 >>> a.update(b)
142 >>> a
143 {1: 2, 2: 3, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
144 >>> a.values()
145 [2, 3, 66, 'alex', 'CN', 'Feale', 404, '170', None]
146 >>> a.keys()
147 [1, 2, 3, 'name', 'country', 'sex', 'birthday', 'Height', 'Occupation']
148 >>> a.viewitems()
149 dict_items([(1, 2), (2, 3), (3, 66), ('name', 'alex'), ('country', 'CN'), ('sex', 'Feale'), ('birthday', 404), ('Height', '170'), ('Occupation', None)])
150 >>> a.viewkeys()
151 dict_keys([1, 2, 3, 'name', 'country', 'sex', 'birthday', 'Height', 'Occupation'])
152 >>> v
153 Traceback (most recent call last):
154   File "<stdin>", line 1, in <module>
155 NameError: name 'v' is not defined
156 >>> b
157 {1: 2, 2: 3, 3: 66}
158 清楚列表b.clear()
159 
160 >>> b.clear()
161 >>> b
162 {}
163 >>> b['asdfa']=232
164 >>> b['sdf']='dfasf'
165 >>> b
166 {'asdfa': 232, 'sdf': 'dfasf'}
167 >>> b
168 b            bool(        bytearray(
169 basestring(  break        bytes(
170 bin(         buffer(   
171 删除字典 del b   
172 >>> del b
173 >>> b
174 Traceback (most recent call last):
175   File "<stdin>", line 1, in <module>
176 NameError: name 'b' is not defined
177 >>> b = {}
178 >>> b['sdf']='dfasf'
179 >>> b
180 {'sdf': 'dfasf'}
181 >>> b.copy()
182 {'sdf': 'dfasf'}
183 浅复制a.copy()  b字典 a字典一样,修改a ,b不变  
184 >>> b=a.copy()
185 >>> a
186 {1: 2, 2: 3, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
187 >>> b
188 {1: 2, 2: 3, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
189 >>> a[2]='T'   ##改a字典的 key  2
190 >>> a
191 {1: 2, 2: 'T', 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
192 >>> b   #查看b  不变
193 {1: 2, 2: 3, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
194 >>> c=b   #赋值字典的方法改一个都被改了
195 >>> c
196 {1: 2, 2: 3, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, 'Height': '170', 'Occupation': None}
197 >>> b['2']='fasdfa'
198 >>> c
199 {1: 2, 2: 3, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, '2': 'fasdfa', 'Height': '170', 'Occupation': None}
200 >>> b[2]=123
201 >>> c
202 {1: 2, 2: 123, 3: 66, 'name': 'alex', 'country': 'CN', 'sex': 'Feale', 'birthday': 404, '2': 'fasdfa', 'Height': '170', 'Occupation': None}
203 >>> 

View Code

 

 

 

八 for 循环

1、for循环 用户按照顺序循环可迭代对象中的内容, PS:break、continue

li = [11,22,33]
for i in li:
    print(li.index(i),i)

九 enumrate 

创建 序列号 

li = [11,22,33]
for k,v in enumerate(li, 1):
    print(k,v)

十 range 和xrange

  迭代循环
  不会先在内存中创建,而是每次循环就创建一次。节约内存。   3版本python只有range了,等同于xrange   指定范围,生成指定的数字

print range(1, 10)
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
print range(1, 10, 2)
# 结果:[1, 3, 5, 7, 9]
 
print range(30, 0, -2)
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]


例如 :
print(range(1,10))
  输出 range(1, 10) 而不是1 2 3.。。10
 

 

range用法: stop不匹配

 range(start,stop,sep)

  比如 range(1,10,2)

    打印1 3 5 7 9 

  range(10,1,-1

      10 9 8 7 ... 2 

 

 

练习题

1、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90…],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}

 

2、查找 查找列表中元素,移动空格,并查找以 a或A开头 并且以 c 结尾的所有元素。     li = [“alec”, ” aric”, “Alex”, “Tony”, “rain”]     tu = (“alec”, ” aric”, “Alex”, “Tony”, “rain”)      dic = {‘k1’: “alex”, ‘k2’: ‘ aric’,  “k3”: “Alex”, “k4”: “Tony”}  
3、输出商品列表,用户输入序号,显示用户选中的商品  利用 enumrate     商品 li = [“手机”, “电脑”, ‘鼠标垫’, ‘游艇’]  
4、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]

 

 

5、用户交互,显示省市县三级联动的选择

dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    }
    "河南": {
        ...
    }
    "山西": {
        ...
    }
 
}

 

答案:

 1 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
list_a=[11,22,33,44,55,66,77,88,99,111]
dic = { "k1":[],"k2":[]}
for i in list_a:
    if i <= 66:
        dic["k1"].append(i)
    else:
        dic["k2"].append(i)

print("\033[33;1m小于66的值:\033[0m%s \n\033[35;1m大于66的值:\033[0m%s " % (dic["k1"],dic["k2"]))

 #易错点:

    if  a条件 or b条件 and c条件   

    如果分级的话用括号包起来

      if  (a条件 or b条件) and  c条件 


#!/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = 'liujianzuo' li = ["alec", " aric", "Alec", "Tony", "rain"] tu = ("adnc", " arlc", "Amx", "Tony", "rain") dic = {'k1': "arm", 'k2': ' apec', "k3": "Alc", "k4": "Tony"} a=[] b=[] c=[] for i in li: key_a=i.strip() if (key_a.startswith("a") or key_a.startswith("A")) and key_a.endswith("c"): a.append(key_a) for tup in tu: key_b = tup.strip() if (key_b.startswith("a") or key_b.startswith("A")) and key_b.endswith("c"): b.append(key_b) for key in dic.keys(): key_c = dic[key].strip() if (key_c.startswith("a") or key_c.startswith("A")) and key_c.endswith("c"): c.append(key_c) print("列表内的符合元素为:",a) print("元组内的符合元素为:",b) print("字典内内的符合元素为:",c)

 

3

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
li = ["手机", "电脑", '鼠标垫', '游艇']
print("商品列表")
for i in enumerate(li,1):
    print(i[0],i[1])


while True:
    chose=input("请选择商品:").strip()
    if len(chose) == 0:
        print("\033[31;1m输入为空,清重新输入!!\033[0m")
        continue
    elif chose.isdigit() == True:
        break
    else:
        print("\033[31;1m你的输入为非数字,请重新输入\033[0m")
        continue
print("\033[31;1m选中的商品是:\033[0m",li[int(chose)-1])

 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
while True:
    salary = input("\033[33;1m请输入你的工资:\033[0m").strip()
    if len(salary) == 0:
        print("\033[31;1m工资不能为空重新输入~~\033[0m")
        continue
    elif salary.isdigit() != True:
        print("\033[31;1m输入必须是数字~~~\033[0m")
        continue
    else:
        break
salary = int(salary)
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
def list_goods():
    print("\033[32;1m欢迎来到商城 ,商品列表:\033[0m")
    n = 1
    for i in goods:
        print(n, i["name"], i["price"])
        n += 1
list_goods()
shop_list = []
while True:
    chose = input("\033[33;1m输入选中的商品 输入 quit 离开:\033[0m").strip()
    if len(chose) == 0:
        print("\033[31;1m选择不能为空重新输入~~\033[0m")
        continue
    elif chose == 'quit':
        while True:
            print("\033[34;1m购物车列表,如果要移除请选择序列号\033[0m")
            for x in enumerate(shop_list, 1):
                print(x[0], x[1])
            del_list = input("\033[33;1m你可以移除商品,输入你的购物车商品编号, 输入 quit 离开:\033[0m")
            if len(del_list) == 0:
                print("\033[31;1m不能为空~~\033[0m")
                continue
            elif del_list == 'quit':
                break
            elif del_list.isdigit() != True:
                print("\033[31;1m必须是个数字\033[0m")
                continue
            elif int(del_list) > len(shop_list):
                print("\033[31;1m物品不存在\033[0m")
                continue
            del_list = int(del_list)
            for i in goods:
                if shop_list[del_list - 1] == i["name"]:
                    salary += i["price"]
                    print(
                        "\033[35;1m移除了商品:%s 返回现金:%s 元,目前余额:%s 元\033[0m" % (shop_list[del_list - 1], i["price"], salary))
            del shop_list[del_list - 1]
        break
    elif chose.isdigit() != True:
        print("\033[31;1m输入必须是数字~~~\033[0m")
        continue

    chose = int(chose)
    if chose > len(goods):
        print("\033[31;1m你选择的商品不存在!!\033[0m")
        continue
    if goods[chose - 1]["price"] <= salary:
        salary -= goods[chose - 1]["price"]
        shop_list.append(goods[chose - 1]["name"])
        print("\033[35;1m你选择了:%s 还剩下工资:%s 你的购物车内有:%s\033[0m" % (goods[chose - 1]["name"], salary, shop_list))
        continue
    else:
        print("\033[31;1m余额不够\033[0m")
        ans = input("你是否想充值?yes=充值 no=返回商城列表:")
        if ans == 'yes':
            while True:
                add_salary = input("输入你的充值额数:").strip()
                if len(add_salary) == 0:
                    add_salary = 0
                    break
                elif add_salary.isdigit() != True:
                    print("\033[31;1m输入必须是数字~~~\033[0m")
                    continue
                else:
                    break
            add_salary = int(add_salary)
            
            salary += add_salary
            print("\033[35;1m充值金额:%s 现在工资:%s 元 \033[0m" % (add_salary, salary))
        elif ans == 'no':
            list_goods()
            continue
balance = salary
if len(shop_list) < 1:
    shop_list = "0件"
print("\033[35;1m购买的商品: %s 余额是:%s\033[0m" % (shop_list, balance))

输出示例:

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 

 

 1 #!/usr/bin/env python
 2 # _*_ coding:utf-8 _*_
 3 __author__ = 'liujianzuo'
 4 chinamap = {
 5     "山东省":{
 6         "济南":["市中区","历下区","天桥区","槐荫区","历城区","长清区","章丘市","平阴县","济阳县","商河县","其他"],
 7         "青岛":["市南区","市北区","城阳区","四方区","李沧区","黄岛区","崂山区","胶南市","胶州市","平度市","莱西市","即墨市","其他"]
 8     },
 9     "北京市":{
10         "北京":["东城区","西城区","崇文区","宣武区","朝阳区","海淀区","丰台区","石景山区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","门头沟区","密云县","延庆县","其他"],
11     },
12     "广东省":{
13         "广州":["越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","番禺区","花都区","南沙区","萝岗区","增城市","从化市","其他"],
14         "深圳":["福田区","罗湖区","南山区","宝安区","龙岗区","盐田区","其他"]
15     },
16     "河北省":{
17         "邯郸":[
18             "成安县","磁县","大名县","肥乡县","馆陶县","广平县","邯郸市","邯郸县","鸡泽县","临漳县","邱县","曲周县","涉县","魏县","武安市","永年县"
19         ],
20         "衡水":[
21             "安平县","阜城县","故城县","衡水市","冀州市","景县","饶阳县","深州市","武强县","武邑县","枣强县"
22         ],
23         "石家庄":[
24             "高邑县","晋州市","井陉县","灵寿县","鹿泉市","平山县","深泽县","石家庄市","无极县","辛集市","新乐市","行唐县","元氏县","赞皇县","赵县","正定县","藁城市","栾城县"
25         ]
26     }
27 }
28 chose=[]
29 def zero():
30     print("\033[31;1m选择不能为空,清重新输入~~\033[0m")
31 def crre():
32     print("\033[31;1m你的选择不正确,清重新输入~~\033[0m")
33 
34 print("\033[32;1m省列表如下:\033[0m\033[0m")
35 for key in chinamap.keys():
36     print(key)
37 while True:
38     sheng=input("\033[33;1m请输入省,quit for leave:\033[0m").strip()
39     if len(sheng) == 0:
40         zero()
41         continue
42     elif sheng == 'quit':
43         break
44     elif sheng not in chinamap.keys():
45         crre()
46         continue
47 
48     else:
49         chose.append(sheng)
50         print("\033[32;1m市列表如下:\033[0m")
51         for key_shi in chinamap[sheng].keys():
52             print(key_shi)
53         while True:
54             shi=input("\033[33;1m请输入市:quit for leave:\033[0m").strip()
55             if len(shi) == 0:
56                 zero()
57             elif shi == 'quit':
58                 print("\033[35;1m你选择的省:%s \033[0m"%(chose[0]))
59                 exit()
60             elif shi not in chinamap[sheng].keys():
61                 crre()
62             else:
63                 chose.append(shi)
64                 print("\033[32;1m县区列表如下:\033[0m")
65                 for key_xian in enumerate(chinamap[sheng][shi],1):
66                     print(key_xian[0],key_xian[1])
67                 while True:
68                     xian=input("\033[33;1m请输入县序号,quti for leave:\033[0m").strip()
69                     if len(xian) == 0:
70                         zero()
71                     elif xian == 'quit':
72                         print("\033[35;1m你选择的省:%s 市是:%s \033[0m"%(chose[0],chose[1]))
73                         exit()
74                     elif xian.isdigit() != True:
75 
76                         print("\033[31;1m必须是 数字\033[0m")
77                         continue
78                     elif int(xian) > len(chinamap[sheng][shi]):
79                         print("\033[31;1m选择不存在\033[0m")
80                         continue
81                     else:
82                         xian=int(xian)
83                         chose.append(chinamap[sheng][shi][xian-1])
84                         break
85                 break
86         break
87 if len(chose) < 1:
88     print("\033[35;1m你什么也没选~~!!\033[0m")
89 else:
90     print("\033[35;1m你选择的省:%s 市是:%s 县是:%s\033[0m"%(chose[0],chose[1],chose[2]))

 

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

 第5题 以序列号的选择 来输出

  知识点

    字典keys 转换为 list

  

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
chinamap = {
"山东省":{
"济南":["市中区","历下区","天桥区","槐荫区","历城区","长清区","章丘市","平阴县","济阳县","商河县","其他"],
"青岛":["市南区","市北区","城阳区","四方区","李沧区","黄岛区","崂山区","胶南市","胶州市","平度市","莱西市","即墨市","其他"]
},
"北京市":{
"北京":["东城区","西城区","崇文区","宣武区","朝阳区","海淀区","丰台区","石景山区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","门头沟区","密云县","延庆县","其他"],
},
"广东省":{
"广州":["越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","番禺区","花都区","南沙区","萝岗区","增城市","从化市","其他"],
"深圳":["福田区","罗湖区","南山区","宝安区","龙岗区","盐田区","其他"]
},
"河北省":{
"邯郸":[
"成安县","磁县","大名县","肥乡县","馆陶县","广平县","邯郸市","邯郸县","鸡泽县","临漳县","邱县","曲周县","涉县","魏县","武安市","永年县"
],
"衡水":[
"安平县","阜城县","故城县","衡水市","冀州市","景县","饶阳县","深州市","武强县","武邑县","枣强县"
],
"石家庄":[
"高邑县","晋州市","井陉县","灵寿县","鹿泉市","平山县","深泽县","石家庄市","无极县","辛集市","新乐市","行唐县","元氏县","赞皇县","赵县","正定县","藁城市","栾城县"
]
}
}
# n = list(chinamap.keys())
#print(n)
# m = list(chinamap[n[0]].keys())
# print(m)
# print(n[0])
# print(m[0])
# print(chinamap[n[0]][m[0]])
# exit()
chose=[]
def zero():
print("\033[31;1m选择不能为空,清重新输入~~\033[0m")
def crre():
print("\033[31;1m你的选择不正确,清重新输入~~\033[0m")


print("\033[32;1m省列表如下:\033[0m\033[0m")
# for key in chinamap.keys():
# print(key)
n = list(chinamap.keys())
n1 = []
shi_list=[]
xian_list=[]
for k,i in enumerate(n,1):
print(k,i)
n1.append(i)

# print("=================",n1)
while True:
sheng=input("\033[33;1m请输入省,quit for leave:\033[0m").strip()
if len(sheng) == 0:
zero()
continue
elif sheng == 'quit':
break
elif sheng.isdigit() != True:
print("\033[31;1m请选择一个数字~~~\033[0m")
continue
elif int(sheng)-1 >= len(n):
print("\033[31;1m选择不存在 out of range\033[0m")
continue
else:
sheng=int(sheng)

chose.append(n1[sheng-1])
print("\033[35;1m你进入省:%s \033[0m"%(chose[0]))
#print(chose)
print("\033[32;1m市列表如下:\033[0m")
shi_dic_list = list(chinamap[n1[sheng-1]])
#print(shi_dic_list)
for k,v in enumerate(shi_dic_list,1):
print(k,v)
shi_list.append(v)
# print("=============",shi_list)
while True:
shi=input("\033[33;1m请输入市:quit for leave:\033[0m").strip()
if len(shi) == 0:
zero()
elif shi == 'quit':
print("\033[35;1m你选择的省:%s \033[0m" % (chose[0]))
exit()
# elif shi not in chinamap[sheng].keys():
# crre()
elif shi.isdigit() != True:
print("\033[31;1m请选择一个数字~~~\033[0m")
continue
elif int(shi) -1 >= len(shi_dic_list):
print("\033[31;1m选择不存在 out of range\033[0m")
continue
else:
shi=int(shi)
chose.append(shi_list[shi-1])

print("\033[35;1m你进入省:%s 市是:%s \033[0m"%(chose[0],chose[1]))

# print(chose)
# exit()
print("\033[32;1m县区列表如下:\033[0m")
for key_xian in enumerate(chinamap[n1[sheng-1]][shi_list[shi-1]],1):
print(key_xian[0],key_xian[1])
xian_list.append(key_xian[1])
while True:
xian=input("\033[33;1m请输入县序号,quti for leave:\033[0m").strip()
if len(xian) == 0:
zero()
elif xian == 'quit':
print("\033[35;1m你选择的省:%s 市是:%s \033[0m"%(chose[0],chose[1]))
exit()
elif xian.isdigit() != True:

print("\033[31;1m必须是 数字\033[0m")
continue
elif int(xian) > len(chinamap[n1[sheng-1]][shi_list[shi-1]]):
print("\033[31;1m选择不存在 out of range\033[0m")
continue
else:
xian=int(xian)
chose.append(xian_list[xian-1])
break
break
break
if len(chose) < 1:
print("\033[35;1m你什么也没选~~!!\033[0m")
else:
print("\033[35;1m你选择的省:%s 市是:%s 县是:%s\033[0m"%(chose[0],chose[1],chose[2]))

输出截图

《python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange 列表中的十六进制或者unicode展示位中文》

    原文作者:众里寻,阑珊处
    原文地址: http://www.cnblogs.com/liujianzuo888/articles/5445798.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞