1. 程式人生 > >Python面試題集答案(4)

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