您的位置:首页 > 编程语言 > Python开发

python程序设计基础2:python数据类型

2014-03-23 12:25 567 查看
从一个简单的例子开始:输入5个数,按从大到小输出。你怎么做?

其实可以按照昨天的一个例题那样子做,但是数据较多,繁琐且容易出错。但是使用python的列表(list)数据类型就不会这样了。

1、列表

先通过如下的例子了解list的一些基本的操作:

>>> a=[1,2,3]

>>> b=[2,3,4]   这就是列表

>>> a+b

[1, 2, 3, 2, 3, 4]

>>> a.append(b)

>>> a

[1, 2, 3, [2, 3, 4]]   这也是列表

>>> a.extend(b)

>>> a

[1, 2, 3, [2, 3, 4], 2, 3, 4]

>>> a=a+b

>>> a

[1, 2, 3, [2, 3, 4], 2, 3, 4, 2, 3, 4]

可见   a=a+b一样的可以实现  a.extend(b)的效果。同时通过上面的例子你也应该知道a.extend(b)和a.append(b)的区别了(这个在机器学习实战38页也用到了)下面我们来实现上面的例子:输入5个值,按顺序输出。

代码:

inputlist=[]

for i in range(5):

    num=input( 'please input the'+str(i+1)+'number:')

    inputlist=inputlist+[num]

print 'the list is:',inputlist

inputlist.sort()

print 'the sorted list is :',inputlist

结果:

please input the1number:34

please input the2number:56

please input the3number:26

please input the4number:78

please input the5number:35

the list is: [34, 56, 26, 78, 35]

the sorted list is : [26, 34, 35, 56, 78]

是不是很简单。特别是这一行inputlist=inputlist+[num] 其中num本来就是一个数字,但是直接加上一个[]符号就将他转化为list了非常的方便。

另外,知道下面的不同:

>>> a=[1,'3',2]

>>> a[1]

'3'

>>> print a[1]

3

list的基本操作在上面都涉及到了。比较和区别可以参见:http://blog.csdn.net/ikerpeng/article/details/18704379

还有一个insert,del,以及几个函数:cmp(),sorted(),reversed()等

>>> a

[1, 'iker']

>>> a.insert(1,'peng')

>>> len(a)

3

>>> sorted(a)

[1, 'iker', 'peng']

>>> a

[1, 'peng', 'iker']

>>> sorted(a,reverse=True)

['peng', 'iker', 1]

>>> a

[1, 'iker', 'peng']

2、元组

元组和list非常的相似,区别在于元组中的数据一旦定义就不能更改,所以也就没有增加和删除的属性了。所以元组更加的安全。并且速度也是比较快的。

元组的特色:

检索元素:

>>> a=(1,'iker',[2,3])

>>> a

(1, 'iker', [2, 3])

>>> type(a)

<type 'tuple'>

>>> a.count('iker')

1

>>> b=a.count('peng')

>>> b

0

返回索引:

>>> a.index(1)

0

赋多值:

>>> x,y,z=a

>>> x

1

>>> y

'iker'

>>> z

[2, 3]

3.字典使用{}定义的一种数据类型,能够设置键值以及它所指向的值。

>>> a={'a':'answer',1:'iker','peng':'iker'}

>>> a['a']

'answer'

>>> a[1]

'iker'

>>> 'iker' in a

False                 不能找到值是否存在,只能找相应的键值。

>>> 'peng' in a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python