Python语言基础与应用 (P23)上机练习:容器类型操作(未完待续)

上机练习:容器类型操作
〉 列表、元组基本操作
+, *, len(), [], in

 1 Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
 2 Type "help", "copyright", "credits" or "license" for more information.
 3 >>> t1=tuple(range(1,10,2))
 4 >>> t1
 5 (1, 3, 5, 7, 9)
 6 >>> t2=tuple(range(2,11,2))
 7 >>> t2
 8 (2, 4, 6, 8, 10)
 9 >>> t1+t2
10 (1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
11 >>> len(t1)
12 5
13 >>> t2[3]
14 8
15 >>> 9 in t1
16 True
17 >>> 7 in t2
18 False
19 >>> L1=list(range(15))
20 >>> L1
21 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
22 >>> L2=L1*3
23 >>> L2
24 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
25 >>> 99 in L2
26 False
27 >>> len(L2)
28 45
29 >>> list(t2)+L1
30 [2, 4, 6, 8, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]


〉 列表、元组高级操作
mylist=[1,2,3,4,5]
切片:获得[2,3,4],获得[3,4,5],获得[3,2,1],
获得[1,3,5]
mytpl=(1,2,3,4,5)同上操作
t='Mike and Tom'
split拆分、 join合成为'Mike/and/Tom

>>> mylist=[1,2,3,4,5]
>>> list1=mylist[1:4]
>>> list1
[2, 3, 4]
>>> list2=mylist[2:]
>>> list2
[3, 4, 5]
>>> list3=mylist[2:0:-1]
>>> list3
[3, 2]
>>> list3=mylist[2::-1]
>>> list3
[3, 2, 1]
>>> list4=mylist[-3::-1]
>>> list4
[3, 2, 1]
>>> list5=mylist[::2]
>>> list5
[1, 3, 5]
>>> mytpl=tuple(mylist)
>>> mytpl
(1, 2, 3, 4, 5)
>>> tu1=mytpl[1:4]
>>> tu1
(2, 3, 4)
>>> tu2=mytpl[2::-1]
>>> tu2
(3, 2, 1)
>>> tu3=mytpl[::2]
>>> tu3
(1, 3, 5)
>>> t='Mike and Tom'
>>> t_new=t.split(' ').join("/")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
>>> t_new=t.split(' ')
>>> t_new
['Mike', 'and', 'Tom']
>>> t_n=str(t_new)
>>> t_n
"['Mike', 'and', 'Tom']"
>>> t_n=t.replace(" ","/")
>>> t_n
'Mike/and/Tom'

总结:split方法中如果不传参,默认以空格分割。list没有join方法,只有str才有。join()中的参数是个序列,可以是list,tuple,set,但最好不要用set,因为set中的元素是无序的。

猜你喜欢

转载自www.cnblogs.com/flyingtester/p/12360964.html
今日推荐