代码改变世界

python day2 list tuple dict str

2016-01-23 22:36  dribs  阅读(288)  评论(0)    收藏  举报

列表

#列表事例

>>> li = list((1,2,3,4,5))
>>> print li
[1, 2, 3, 4, 5]


>>> li2 = ['a','b','c','d']
>>> print li2
['a', 'b', 'c', 'd']
>>>

#列表尾部增加元素
>>> li.append(6)
>>> li
[1, 2, 3, 4, 5, 6]


#清空列表内的元素,适用于py3
li.clear()
print(li)
[]


#列表的拷贝(深浅拷贝)(忽略)
li = [1,2,3,4,]
li3 = li.copy()
li3.append(678,)
print(li)
print(li3)
liid = id(li)
liid3 = id(li3)
print(liid,liid3)

[1, 2, 3, 4]
[1, 2, 3, 4, 678]
35707080 35737992

 

#extend合并两个列表或者把列表和元组合并
>>> li.extend([1,2])
>>> li
[1, 2, 3, 4, 5, 6, 1, 2]

 

#count判断某个元素出现的次数
>>> li.count(1)
2

 


#index获取列表内元素的索引下表
>>> li.index(6)
5


#insert指定下标,插入元素
>>> li.insert(2,'abc')
>>> li
[1, 2, 'abc', 3, 4, 5, 6, 1, 2]

 

#pop移除某一项,加下标
>>> li
[1, 2, 'abc', 3, 4, 5, 6, 1, 2]
>>> res = li.pop(3)
>>> print res
3
>>> print li
[1, 2, 'abc', 4, 5, 6, 1, 2]

 

#remove删除--pop   加值,pop是加下标
>>> li.remove('abc')
>>> li
[1, 2, 4, 5, 6, 1, 2]

 


#reverse反向排序
>>> li
[1, 2, 4, 5, 6, 1, 2]
>>> li.reverse()
>>> li
[2, 1, 6, 5, 4, 2, 1]

 

#sort排序
>>> li
[2, 1, 6, 5, 4, 2, 1]
>>> li.sort()
>>> li
[1, 1, 2, 2, 4, 5, 6]
>>>

英文介绍

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass
View Code


字典

 

>>> dic = {'k1':'v1'}
>>> dic2 = dict(k1='v1',k2='v2')

>>> print dic2

{'k2': 'v2', 'k1': 'v1'}
>>> print dic
{'k1': 'v1'}

 

#fromkeys拿到key指定一个Value生成一个新的字典,其实是在内部做了一次for循环

dic = dict(k1='v1',k2='v2')
new_dic = dic.fromkeys(['k3','k2'],'v3')
print(new_dic)
print(dic)

{'k3': 'v3', 'k2': 'v3'}
{'k2': 'v2', 'k1': 'v1'}

 

#get如果key不存在会默认返回一个“None”不会报错,也可设置默认值。如果key存在显示已存在的

>>> dic
{'k1': 'v1'}
>>> print dic['k1']
v1
>>> print dic['k2']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k2'

>>> print dic.get('k2')
None

>>> print dic.get('k2','v2')
v2

>>> print dic.get('k1','v2')
v1

 

#keys values itmes    keys获取所有的key,values获取所有的vales。 items获取键值对

>>> dic2
{'k2': 'v2', 'k1': 'v1'}
>>> print dic2.keys()
['k2', 'k1']
>>> print dic2.values()
['v2', 'v1']
>>> print dic2.items()
[('k2', 'v2'), ('k1', 'v1')]

#这就可以进行for循环了

>>> print dic2.items()
[('k2', 'v2'), ('k1', 'v1')]
>>> for k in dic2.keys():
... print k
...
k2
k1
>>> for v in dic2.values():
... print v
...
v2
v1

>>> for itk,itv in dic2.items():
... print itk,itv
...
k2 v2
k1 v1

 

#pop 拿走一个,需添加k参数,因为字典是无序的

>>> dic2
{'k2': 'v2', 'k1': 'v1'}
>>> dic2.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop expected at least 1 arguments, got 0
>>> dic2.pop('k2')
'v2'
>>> dic2
{'k1': 'v1'}
>>>

 

#popitem 随机取走一个 没什么用

>>> dic2['k2'] = 'v2'
>>> dic2
{'k2': 'v2', 'k1': 'v1'}
>>> res = dic2.popitem()
>>> print res
('k2', 'v2')
>>> dic2
{'k1': 'v1'}
>>>

 

#setdefault给字典设置值,默认等于“None”。没什么用

>>> dic2.setdefault('k4','v4')
'v4'
>>> dic2
{'k3': None, 'k1': 'v1', 'k4': 'v4'}

 

#update  更新字典

>>> dic2
{'k3': None, 'k1': 'v1', 'k4': 'v4'}
>>> dic2.update({'k5':123})
>>> dic2
{'k3': None, 'k1': 'v1', 'k5': 123, 'k4': 'v4'}
>>>

def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass
View Code

 

字符串

>>> name = 'eric'
>>> print type(name)
<type 'str'>
>>> print dir(name)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get
slice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo
d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook
__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center',
'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index
', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', '
rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', '
strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

#__contains__  包含  相当于in

 

 capitalize  首字母换成大写

casefold     所有字母换成小写

center        填充

count         计数

encode        编码转换

endswith      以什么结尾

expandtabs  把tab(\t)转成空格   默认一个tab8个空格

find              查找,返回下标,无则返回-1     index查找如果无则抛出异常

format          字符串格式化

>>> name = "alex {0} is {1}"
>>> name.format('sb','eric')
'alex sb is eric'
>>>

>>> name = "alex {a} is {b}"
>>> name.format(b='sb',a='eric')
'alex eric is sb'

join               拼接

>>> li = ['a','l','e','x','s','b']
>>> res = "".join(li)
>>> print res
alexsb
>>>

>>> res = "-".join(li)
>>> print res
a-l-e-x-s-b
>>>

ljust                  类似于center  放到左边

lower                  变小写

strip                   两边空格全去掉     lstrip  去左边    rstrip去右边

maketrans           和translate结合用

partition              分割成元组

>>> name1 = 'alexissb'
>>> name1.partition('is')
('alex', 'is', 'sb')

replace                  全部替换,加个数转换几个

>>> name1.replace('a','o')
'olexissb'

 

split                       指定字符分割字符串转换成列表

startswith               以什么开头

swapcase                大小写转换

title                        

upper