可爱的python之快速入门

2009年11月14日  |  6:49 下午分类:python  |  

python所支持的数据类型:
整型、长整型、布尔型、浮点型、复数、字符串、列表(list)、元组(Tuple)、字典(Dict)、object

python能支持理论意义上的长整型,如C#中的长整型是Int64,即最大值为2的64次方,而python中的长整型只与机器的虚拟内存大小有关,你完全不用考虑溢出这样的异常。

python是一种动态语言,虽然在定义变量时无需定义变量的类型,但并不意味着在运行的过程中,系统会自动更改变量的类型,所以,python是一种强类型的动态语言,它与asp/javascript/php完全不一样,比如:

>>> a=123
>>> print 'input '+ a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>

此时出现了一个异常“无法将字符串类型与数字类型的数据做连接操作”,而这样的语法在php/asp中是完全可行的。

bool型在python中用True/False来表示,当然,空字符串、0、空元组、空列表、空字典都会认为一个False值。

字符串是位于成对的单引、双引、三单引、三双引之间的字符。

列表类似于c#中的ArrayList,通过下标来访问。

元组是一个只读的列表。

字典类似于c#中的hashtable,它的键必须是可被hash的。

列表的定义方法:

>>> li = [1,2,3,4,5]
>>> li_1 = []
>>> li_2 = range(10)
>>> li
[1, 2, 3, 4, 5]
>>> li_1
[]
>>> li_2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

元组的定义与列表类似,只是把[]换成了(),但要注意:如果元组中只有一个元素,也要在该元素的后面加上,号

>>> tu = (1,2,3)
>>> tu_2 = (2)       #这里会认为tu_2是一个int类型
>>> type(tu)
<type 'tuple'>
>>> type(tu_2)
<type 'int'>
>>> tu_2 = (2,)
>>> type(tu_2)
<type 'tuple'>

字典用大括号标识,多个元素用,分开,这点跟Json一样

>>> dic = {'name':'yibin','email':'yibin.net@gmail.com'}
>>> type(dic)
<type 'dict'>
>>> dic
{'name': 'yibin', 'email': 'yibin.net@gmail.com'}

可以用keys()方法得到该字典的键,用values()方法得到值,用items()方法得到以键-值为一组的列表

['name', 'email']
['yibin', 'yibin.net@gmail.com']
[('name', 'yibin'), ('email', 'yibin.net@gmail.com')]

可以把多个列表相加,如:

    a = [1,2,3,4]
    b = [5,6,7,8]
    c = a+b
    print a
    print b
    print c
    a.append(b)
    c.extend(b)
    print a
    print c
运行结果:
[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, [5, 6, 7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8, 5, 6, 7, 8]
请按任意键继续. . .

注意看append与extend方法的区别。

想得知list/tuple/str/dict有哪些可用的方法和属性,可以用dir函数;可以用help()函数获取相应的帮助

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delsli
ce__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gets
lice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '
__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__r
educe_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__
', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'p
op', 'remove', 'reverse', 'sort']
>>> dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__g
t__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul_
_', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__',
'__setattr__', '__str__']
>>>

不要惊讶于dir(tuple)为什么没有方法可用,因为tuple是只读的。

获取关于list的extend方法的帮助:

>>> help(list.extend)
Help on method_descriptor:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable
>>>
转载时务必以超链接形式标明文章原始出处和作者信息。

相关文章

  • 暂无相关日志

发表您的评论

2412151751091918111201478131663