1. 程式人生 > >python-序列物件方法(38)

python-序列物件方法(38)

>>> from random import randint
>>> alist = list()
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> list((10,20,30))   #元組轉換成列表
[10, 20, 30]

>>> astr = str()
>>> str(10)    #將數字轉換成字串
'10'
>>> str(['h','e','l','l','o']) #將列表轉換成字串
"['h', 'e', 'l', 'l', 'o']"

>>> antuple = tuple()
>>> tuple('hello') #將字串轉換成元組
('h', 'e', 'l', 'l', 'o')

>>> num_list = [randint(1,100) for i in range(10)]
>>> num_list
[18, 92, 21, 89, 64, 6, 91, 53, 4, 68]
>>> max(num_list)
92
>>> min(num_list)
4

>>> alist = [10,'john']
>>> list(enumerate(alist)) #enumerate 函式用於遍歷序列中的元素以及它們的下標
[(0, 10), (1, 'john')]

>>> for i in range(len(alist)):
...     print('%s:%s' % (i,alist[i]))
... 
0:10
1:john

>>> for item in enumerate(alist):
...     print('%s:%s' % (item[0],item[1]))
... 
0:10
1:john

>>> for ind,val in enumerate(alist):
...     print('%s:%s' % (ind,val))
... 
0:10
1:john

>>> atuple = (96,97,40,75,58,34,69,29,66,90)
>>> sorted(atuple) #排序
[29, 34, 40, 58, 66, 69, 75, 90, 96, 97]
>>> sorted('hello')
['e', 'h', 'l', 'l', 'o']

>>> for i in reversed(atuple): #reversed(),反轉
...     print(i,end=',')
... 
90,66,29,69,34,58,75,40,97,96,>>>