python基礎之元組,列表

黎明的燼發表於2017-06-19

>>> menber=["小甲魚","不定","怡欣","mt"]

>>> for each in menber:
	print(each,len(each))


python的內建物件預覽:

Number(數字):3.0145,1234,99L,3+4j(負數常量)

String(字串):`sapm`,”紅色經`kkk`典”

List(列表):[1,[2,`three points`],4]

Dictionary(字典):{`food`:`spam`,`taste`:`yum`}

Tuple(元組):(1,`spam`,4,`U`)

File(檔案):text=open{`segg`,`r`}.read()


python的比較操作符與java一樣

> 大於

< 小於

————————————————————

條件分支語法:

①if 條件:

→縮排   條件為真執行

else:

→縮排條件為假執行操作

②while

while 條件:

條件為真執行操作


and邏輯操作運算子


隨機:random模組

randint(),會返回一個隨機整數




型別轉換

整數→字串str()例如str(132412)變為`132412`

整數→浮點型float()

int()注意:浮點數轉換為整數時會採取截斷處理。



獲取型別資訊

type()返回型別

例子:a=`reui`

type(a)


isinstance()方法 

例子:isistance(`eq`,str)

返回一個布林型別值。是否是這個型別


迴圈:

while  迴圈:

while 條件:、

迴圈體

for迴圈:

for   目標  in  表示式列表:

迴圈體


range() 

語法:range() ([strat,] stop[,step=1])

step=1,預設的值為1;range作用是生產一個從start引數的值開始到stop引數的數字序列



列表:

因為python中變數沒有型別,而陣列元素的型別是相等的,所以python沒有陣列,所以列表是加強版的陣列~

①建立普通列表

例如:陣列名=[1,23,3,4,4,4,4]

②混合列表(列表的成員變數型別包括很多型別)

③建立空列表:empty=[]


對列表的操作:

顯示長度→len(列表名)

向列表中新增元素→列表名.append(變數)   

        向列表中插入列表→列表名.extend([變數1,變數2 ,] )

插入列表中任意位置→列表名.insert(2,”ds”)  插入第二個位置


刪除列表元素→remove(“成員變數”)   

del  menber[4]→刪除第五個成員

       返回並刪除該值→pop(5)   刪除第6個元素

列表的分片slice

 menber[1:3]   :將會顯示第二個和第三個成員變數,形成了對源列表的拷貝!


列表的比較操作符:

>>> list1=[123,345]
>>> list2=[234,123]
>>> list1>list2
False

只要列表1的第一個元素大於列表2,那麼,後面的數就不用比較了。

+號運算

>>> list1+"xiaojiayu"
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    list1+"xiaojiayu"
TypeError: can only concatenate list (not "str") to list
>>> list1+list2
[123, 345, 234, 123]
>>> 

*號運算

>>> list1*3
[123, 345, 123, 345, 123, 345]


in運算子  只能夠影響一層

>>> list5=[123,["xiaojiayu","why"]]
>>> list4=[123,"xiaojiayu","why"]
>>> "why" in list4
True
>>> "why" in list5
False
>>> 


檢視list的內建函式:

>>> dir(list)
[`__add__`, `__class__`, `__contains__`, `__delattr__`, `__delitem__`, `__dir__`, `__doc__`, `__eq__`, `__format__`, `__ge__`, `__getattribute__`, `__getitem__`, `__gt__`, `__hash__`, `__iadd__`, `__imul__`, `__init__`, `__iter__`, `__le__`, `__len__`, `__lt__`, `__mul__`, `__ne__`, `__new__`, `__reduce__`, `__reduce_ex__`, `__repr__`, `__reversed__`, `__rmul__`, `__setattr__`, `__setitem__`, `__sizeof__`, `__str__`, `__subclasshook__`, `append`, `clear`, `copy`, `count`, `extend`, `index`, `insert`, `pop`, `remove`, `reverse`, `sort`]
>>> 

使用:

count 計數

>>> list4.count(123)
1


轉置reverse()

排序sort(0):預設是從小到大排序

>>> list6=[1,0,9,5,4,7,6,2,11,10]
>>> list6.sort()
>>> list6
[0, 1, 2, 4, 5, 6, 7, 9, 10, 11]
>>> list6.reverse()
>>> list6
[11, 10, 9, 7, 6, 5, 4, 2, 1, 0]
>>> 

或者

>>> list6.sort(reverse=True)
>>> list6
[11, 10, 9, 7, 6, 5, 4, 2, 1, 0]
>>> 


列表的複製:

>>> list7=list6[2:9]
>>> list7
[9, 7, 6, 5, 4, 2, 1]

如果是用=號時,就是給這個列表起了另一個名字,而分片兒複製則會在記憶體中實實在在的分配儲存空間。




元組:戴上了加鎖的列表(不能隨意插入,刪除等操作)

>>> tuple1=(1,2,3,5,8,6,9)
>>> tuple1
(1, 2, 3, 5, 8, 6, 9)
>>> tuple1[3]
5
>>> tuple1[1:3]
(2, 3)
>>> temp=(1)
>>> type(temp)
<class `int`>
>>> type(temp1=(1,))
TypeError: type() takes 1 or 3 arguments
>>> temp=(1,)
>>> type(temp)
<class `tuple`>
>>> 

插入操作:(生成新的元組)

>>> temp=("意境","和","下架與")
>>> temp=temp[:2]+("哇")+temp[2:]
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    temp=temp[:2]+("哇")+temp[2:]
TypeError: can only concatenate tuple (not "str") to tuple
>>> temp=temp[:2]+("哇",)+temp[2:]
>>> temp
(`意境`, `和`, `哇`, `下架與`)
>>> 

字串之內建方法

>>> str=`i am fool ,yami`
>>> str
`i am fool ,yami`
>>> find("fool")
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    find("fool")
NameError: name `find` is not defined
>>> find(`fool`)
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    find(`fool`)
NameError: name `find` is not defined
>>> str.find(`fool`)
5
>>> str.join(`123`)
`1i am fool ,yami2i am fool ,yami3`
>>> "{a} love {b} {c}".format("i" ,"want" ,"to do")
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    "{a} love {b} {c}".format("i" ,"want" ,"to do")
KeyError: `a`
>>> "{a} love {b} {c}".format(a="i" ,b="want" ,c="to do")
`i love want to do`
>>> "{1} love {2} {3}".format("i" ,"want" ,"to do")
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    "{1} love {2} {3}".format("i" ,"want" ,"to do")
IndexError: tuple index out of range
>>> "{0} love {1} {2}".format("i" ,"want" ,"to do")
`i love want to do`
>>> 

序列:

列表,陣列和字串的共同點

可以通過索引得到每個元素

索引預設為從0開始

可以通過分片的方法得到一個範圍內的元素的集合

共同操作符


list()將一個可迭代物件轉換為列表

list(iterable) -> new list initialized from iterable`s items

>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable`s items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None



相關文章