Python面试题集答案(4)

7、如何知道一个python对象的类型?

主要有两个方法来进行判断:type()、isinstance()方法。

<pre name="code" class="python">>>> import types
>>> a = 'aaaa'
>>> type(a)
<type 'str'>
>>> b=123
>>> type(b)
<type 'int'>

 
 

>>> a = 'aaaa'
>>> isinstance(a,str)
True
>>> b=123
>>> isinstance(b,int)
True
type用于返回对象类型。

isinstance(obj,type[])用于判断obj是否是一个已知类型。


在我实际使用时发现当我判断一个list时会报错,不清楚这是什么原因。

>>> D = ['a','1','+']
>>> type(D)
<type 'list'>
>>> isinstance(D,list)

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    isinstance(D,list)
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
希望有清楚这个地方的朋友能帮我解答一下。


8、介绍一下Python下range()函数的用法?

range()方法算是python比较常用的一个方法。在for循环中也经常出现。

a、基本用法

>>> range(1,5)
[1, 2, 3, 4]
>>> range(1,9,2)
[1, 3, 5, 7]
>>> range(5)
[0, 1, 2, 3, 4]

b、循环中的应用

#冒泡排序:
array = [1, 2, 5, 3, 6, 8, 4]
for i in range(len(array) - 1, 0, -1):
    for j in range(0, i):
        if array[j] > array[j + 1]:
            array[j], array[j + 1] = array[j + 1], array[j]
print array

参考:http://www.cnblogs.com/buro79xxd/archive/2011/05/23/2054493.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值