python數據類型詳解及列表字典集合推導式詳解

一.運算符

Python語言支持如下類型的運算符:html

  • 算術運算符

http://images2015.cnblogs.com/blog/425762/201510/425762-20151025004451692-544714036.png

如:python

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = 6
print(a + b)

 

  • 比較運算符

例:git

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = 6
if a < b:
    print(True)
else:
    print(False)

 

  • 賦值運算符

例:sql

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = a
print(b)

 

  • 邏輯運算符

例:編程

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = 6
if a >4 and b < 10:
    print(True)
else:
    print(False)

 

  • 成員運算符

例:api

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "a"
list = ['a','b']

if value in list:
    print(True) 

二.數據類型

  1. 數字

int(整形),數字數據類型用於存儲數值數組

Python 支持三種不一樣的數值類型:app

  • 整型(Int) - 一般被稱爲是整型或整數,是正或負整數,不帶小數點。Python3 整型是沒有限制大小的,能夠看成 Long 類型使用,因此 Python3 沒有 Python2 的 Long 類型。
  • 浮點型(float) - 浮點型由整數部分與小數部分組成,浮點型也可使用科學計數法表示(2.5e2 = 2.5 x 102 = 250)
  • 複數- 複數由實數部分和虛數部分構成,能夠用a + bj,或者complex(a,b)表示, 複數的實部a和虛部b都是浮點型
class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.
    
    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by '+' or '-' and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    """
    def bit_length(self): 
        """ 返回表示該數字的時佔用的最少位數 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ 返回該複數的共軛複數 """
        """ Returns self, the complex conjugate of any int. """
        pass

    def __abs__(self):
        """ 返回絕對值 """
        """ x.__abs__() <==> abs(x) """
        pass

    def __add__(self, y):
        """ x.__add__(y) <==> x+y """
        pass

    def __and__(self, y):
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): 
        """ 比較兩個數大小 """
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __coerce__(self, y):
        """ 強制生成一個元組 """ 
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y): 
        """ 相除,獲得商和餘數組成的元組 """ 
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y): 
        """ x.__div__(y) <==> x/y """
        pass

    def __float__(self): 
        """ 轉換爲浮點類型 """ 
        """ x.__float__() <==> float(x) """
        pass

    def __floordiv__(self, y): 
        """ x.__floordiv__(y) <==> x//y """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, name): 
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        """ 內部調用 __new__方法或建立對象時傳入參數使用 """ 
        pass

    def __hash__(self): 
        """若是對象object爲哈希表類型,返回對象object的哈希值。哈希值爲整數。在字典查找中,哈希值用於快速比較字典的鍵。兩個數值若是相等,則哈希值也相等。"""
        """ x.__hash__() <==> hash(x) """
        pass

    def __hex__(self): 
        """ 返回當前數的 十六進制 表示 """ 
        """ x.__hex__() <==> hex(x) """
        pass

    def __index__(self): 
        """ 用於切片,數字無心義 """
        """ x[y:z] <==> x[y.__index__():z.__index__()] """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """ 構造方法,執行 x = 123 或 x = int(10) 時,自動調用,暫時忽略 """ 
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is floating point, the conversion truncates towards zero.
        If x is outside the integer range, the function returns a long instead.
        
        If x is not a number or if base is given, then x must be a string or
        Unicode object representing an integer literal in the given base.  The
        literal can be preceded by '+' or '-' and be surrounded by whitespace.
        The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
        interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        # (copied from class doc)
        """
        pass

    def __int__(self): 
        """ 轉換爲整數 """ 
        """ x.__int__() <==> int(x) """
        pass

    def __invert__(self): 
        """ x.__invert__() <==> ~x """
        pass

    def __long__(self): 
        """ 轉換爲長整數 """ 
        """ x.__long__() <==> long(x) """
        pass

    def __lshift__(self, y): 
        """ x.__lshift__(y) <==> x<<y """
        pass

    def __mod__(self, y): 
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y): 
        """ x.__mul__(y) <==> x*y """
        pass

    def __neg__(self): 
        """ x.__neg__() <==> -x """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): 
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __nonzero__(self): 
        """ x.__nonzero__() <==> x != 0 """
        pass

    def __oct__(self): 
        """ 返回改值的 八進制 表示 """ 
        """ x.__oct__() <==> oct(x) """
        pass

    def __or__(self, y): 
        """ x.__or__(y) <==> x|y """
        pass

    def __pos__(self): 
        """ x.__pos__() <==> +x """
        pass

    def __pow__(self, y, z=None): 
        """ 冪,次方 """ 
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
        pass

    def __radd__(self, y): 
        """ x.__radd__(y) <==> y+x """
        pass

    def __rand__(self, y): 
        """ x.__rand__(y) <==> y&x """
        pass

    def __rdivmod__(self, y): 
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y): 
        """ x.__rdiv__(y) <==> y/x """
        pass

    def __repr__(self): 
        """轉化爲解釋器可讀取的形式 """
        """ x.__repr__() <==> repr(x) """
        pass

    def __str__(self): 
        """轉換爲人閱讀的形式,若是沒有適於人閱讀的解釋形式的話,則返回解釋器課閱讀的形式"""
        """ x.__str__() <==> str(x) """
        pass

    def __rfloordiv__(self, y): 
        """ x.__rfloordiv__(y) <==> y//x """
        pass

    def __rlshift__(self, y): 
        """ x.__rlshift__(y) <==> y<<x """
        pass

    def __rmod__(self, y): 
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y): 
        """ x.__rmul__(y) <==> y*x """
        pass

    def __ror__(self, y): 
        """ x.__ror__(y) <==> y|x """
        pass

    def __rpow__(self, x, z=None): 
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
        pass

    def __rrshift__(self, y): 
        """ x.__rrshift__(y) <==> y>>x """
        pass

    def __rshift__(self, y): 
        """ x.__rshift__(y) <==> x>>y """
        pass

    def __rsub__(self, y): 
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y): 
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __rxor__(self, y): 
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sub__(self, y): 
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y): 
        """ x.__truediv__(y) <==> x/y """
        pass

    def __trunc__(self, *args, **kwargs): 
        """ 返回數值被截取爲整形的值,在整形中無心義 """
        pass

    def __xor__(self, y): 
        """ x.__xor__(y) <==> x^y """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分母 = 1 """
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 虛數,無心義 """
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分子 = 數字大小 """
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 實屬,無心義 """
    """the real part of a complex number"""

int
View Code

 

 

2.布爾值ide

真或者假,1或者0函數

 

3.字符串

字符串是python中最多見類型,咱們一般用單引號('')或者雙引號("")來建立

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "a"
print(value)
字符串經常使用功能:
  • 移除空白

例;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = " a "
ret = value.strip()
print(ret)

 

  • 分割

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value.split(',')
print(ret)

 

  • 長度

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value.__len__()
print(ret)

 

  • 索引

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value[0]
print(ret)

 

  • 切片

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value[0:6]
print(ret)

字符串內建函數

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
capitalize()
將字符串的第一個字符轉換爲大寫
"""
value = " hello,world "
ret = value.capitalize()
print(ret)
"""
center(width, fillchar)
返回一個指定的寬度 width 居中的字符串,fillchar 爲填充的字符,默認爲空格
"""
ret = value.center(30)
print(ret)

"""
count(str, beg= 0,end=len(string))
返回 str 在 string 裏面出現的次數,若是 beg 或者 end 指定則返回指定範圍內 str 出現的次數
"""
ret = value.count('l')
print(ret)
"""
decode(encoding='UTF-8',errors='strict')
使用指定編碼來解碼字符串。默認編碼爲字符串編碼
encode(encoding='UTF-8',errors='strict')
以 encoding 指定的編碼格式編碼字符串

temp = "中文"
#解碼,須要指定原來是什麼編碼
temp_unicode = temp.decode('utf-8')
#編碼,須要指定要編成什麼編碼
temp_gbk = temp_unicode.encode('gbk')
print(temp_gbk)
"""
"""
endswith(suffix, beg=0, end=len(string))
檢查字符串是否以某字符串結尾若是是,返回 True,不然返回 False.
"""
ret = value.endswith('d')
print(ret)
"""
expandtabs(tabsize=8)
把字符串 string 中的 tab 符號轉爲空格,tab 符號默認的空格數是 8
"""
ret = value.expandtabs()
print(ret)
"""
find(str, beg=0 end=len(string))
檢測 str 是否包含在字符串中 中,則檢查是否包含在指定範圍內,若是是返回開始的索引值,不然返回-1
"""
ret = value.find('h')
print(ret)

"""
index(str, beg=0, end=len(string))
跟find()方法同樣,只不過若是str不在字符串中會報一個異常,使用find方法最佳
"""
"""
isdigit()
若是字符串只包含數字則返回 True 不然返回 False
"""
ret = value.isdigit()
print(ret)

"""
lstrip()
截掉字符串左邊的空格
"""
ret = value.lstrip()
print(ret)

"""
rstrip()
刪除字符串字符串末尾的空格
"""
ret = value.rstrip()
print(ret)
"""
split(str="", num=string.count(str))
num=string.count(str)) 以 str 爲分隔符截取字符串
"""
ret = value.split(',')
print(ret)

"""
strip([chars])
去除左右空格
"""
ret = value.strip()
print(ret)

"""
title()
返回"標題化"的字符串,就是說全部單詞都是以大寫開始,其他字母均爲小寫
"""
ret = value.title()
print(ret)

python字符串格式化符號:

 

4.列表

列表中每一個位置都分配一個數字,從0開始,依此類推

基本操做:

  • 索引
  • 切片
  • 追加
  • 刪除
  • 長度
  • 循環
  • 包含

建立列表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = ['a','b']

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
索引
"""
list = ['a','b'] ret = list[0] print(ret)
  切片
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
切片
"""
list = ['a','b','c'] ret = list[0:2] print(ret)

  追加

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
追加
"""
list = ['a','b','c']
list.append('d')
print(list)

刪除

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
刪除索引1
"""
list = ['a','b','c'] print(list) del list[1] print(list)

長度

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = ['a','b','c']
ret=list.__len__()
print(ret)

  循環

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = ['a','b','c']

for i in list:
    print(i)

  包含

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = ['a','b','c']
list2 = ['d','e']
total = [list + list2]
print(total)

列表中內置函數

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
排序
"""
list = [1,4,2,3,4,5,10,3]
list.sort()
print(list)

"""
list.count(obj)
統計某個元素在列表中出現的次數
"""
ret = list.count(3)
print(ret)

"""
list.extend(seq)
在列表末尾一次性追加另外一個序列中的多個值(用新列表擴展原來的列表)
"""
list2 = [100,101,105]
list.extend(list2)
print(list)

"""
list.pop(obj=list[-1])
移除列表中的一個元素(默認最後一個元素),而且返回該元素的值
"""
list.pop()
print(list)
"""
list.remove(obj)
移除列表中某個值的第一個匹配項
"""
list.remove(1)
print(list)
"""
list.reverse()
反向列表中元素
"""
list.reverse()
print(list)
"""
list.clear()
清空列表
"""
list.clear()
print(list)

 

5.元組

 

Python 的元組與列表相似,不一樣之處在於元組的元素不能修改。

 

元組使用小括號,列表使用方括號

建立元組

#!/usr/bin/env python
# -*- coding:utf-8 -*-
tup = ('a','b','c')
基本操做:
  • 索引
  • 切片
  • 循環
  • 長度
  • 包含
#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = ['a', 'b', 'c']

"""
tuple(seq)
將列表轉換爲元組
"""
tup = tuple(list)
print(tup)

 

6.字典

字典的每一個鍵值(key=>value)對用冒號(:)分割,每一個對之間用逗號(,)分割,整個字典包括在花括號({})中

建立字典

person = {"name": "liu", 'age': 18}

鍵必須是惟一的,值沒必要

  經常使用操做:

  • 索引
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

dic1 = dic["name"]
print(dic1)

 

  • 新增
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

dic["address"] = "beijing"
print(dic)

 

  • 刪除
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

dic["address"] = "beijing"
del dic["age"]
print(dic)

 

  • 鍵、值、鍵值對
  • 循環
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

for key,value in dic.items():
    print(key,value)

 

  • 長度
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

print(len(dic))

字典內建函數

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """

    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(S, v=None): # real signature unknown; restored from __doc__
        """
        dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
        v defaults to None.
        """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根據key獲取值,d是默認值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False

    def items(self): # real signature unknown; restored from __doc__
        """ 全部項的列表形式 """
        """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
        return []

    def iteritems(self): # real signature unknown; restored from __doc__
        """ 項可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass

    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass

    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ 全部的key列表 """
        """ D.keys() -> list of D's keys """
        return []

    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__
        """ 若是key不存在,則建立,若是存在,則返回已存在的值且不修改 """
        """ 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
        """ 更新
            {'name':'alex', 'age': 18000}
            [('name','sbsbsb'),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, 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() -> list of D's values """
        return []

    def viewitems(self): # real signature unknown; restored from __doc__
        """ 全部項,只是將內容保存至view對象中 """
        """ D.viewitems() -> a set-like object providing a view on D's items """
        pass

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

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

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

dict
View Code

 注:通常字符串,只要執行一個功能,會生成一個新內容,原內容不變,追加除外

list,tuple,dict,執行一個功能是原內容進行變化

三.for循環

Python for循環能夠遍歷任何序列的項目,如一個列表或者一個字符串,格式以下

for value in seq:
    do xx

#!/usr/bin/env python
# -*- coding:utf-8 -*-

list = [1,2,5,7]
for i in list:
    print(i)

也能夠break,continue

#!/usr/bin/env python
# -*- coding:utf-8 -*-

list = [1,2,5,7]
for i in list:
    if i == 5:
        break
    print(i)
#!/usr/bin/env python
# -*- coding:utf-8 -*-

list = [1,2,5,7]
for i in list:
    if i == 5:
        continue
    print(i)

2.enumrate

爲可迭代的對象添加序號

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

li = [11,22,33]
for k,v in enumerate(li, 1):
    print(k,v)

 

3.range和xrange

指定範圍,生成指定的數字

#!/usr/bin/env python
# -*- coding:utf-8 -*-

for i in range(10):
    print(i)

 四.練習

列表,字符串,元組,字典之間相互轉換

#!/usr/bin/env python
# -*- coding:utf-8 -*-
st = "hello"
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
#列表轉無組
tup = tuple(li)
print(tup)
#元組轉列表
lis = list(tu)
print(lis)
#字典轉列表
tup_list = list(dic.values())
print(tup_list)
#str轉list
str_list = list(st)
print(str_list)

 2.列表操做

更換列表元素

li = ['a','b']
li[1] = 'c'
print(li)

將列表轉換爲字典的key並按照10開始向後遞增

li = ['a','b','c']
dic = {}
for key,v in enumerate(li,10):
    print(key,v)
    dic[key]=v
print(dic)

 

 

五.模擬題

一、元素分類

有以下值集合 [11,22,33,44,55,66,77,88,99,90...],將全部大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
即: {'k1': 大於66的全部值, 'k2': 小於66的全部值}

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
需求:有以下值集合 [11,22,33,44,55,66,77,88,99,90]
將全部大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中
"""

list = [11,22,33,44,55,66,77,88,99,90]
dic = {
    "key1": [],
    "key2": []
}
for i in list:
    if i > 66:
        dic['key1'].append(i)
    else:
        dic['key2'].append(i)
print(dic)

 

 

二、查找
查找列表中元素,移除每一個元素的空格,並查找以 a或A開頭 而且以 c 結尾的全部元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}\
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
查找列表中元素,移動空格,並查找以 a或A開頭 而且以 c 結尾的全部元素
"""

li = ["alec", " Aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
list1 = list(tu)
list2 = list(dic.values())
newlist = li + list1 + list2
for i in newlist:
    ret = i.strip()
    if (ret.startswith('a') or ret.startswith('A')) and ret.endswith('c'):
        print(ret)

 

 
三、輸出商品列表,用戶輸入序號,顯示用戶選中的商品
    商品 li = ["手機", "電腦", '鼠標墊', '遊艇']
#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
輸出商品列表,用戶輸入序號,顯示用戶選中的商品
商品 li = ["手機", "電腦", '鼠標墊', '遊艇']
"""
li = ["手機", "電腦", '鼠標墊', '遊艇']
for key,i in enumerate(li):
    print(key,i)
inp = input("please input your chose:")
chose = int(inp)
print(li[chose])

 

 

 

四、購物車

功能要求:

  • 要求用戶輸入總資產,例如:2000
  • 顯示商品列表,讓用戶根據序號選擇商品,加入購物車
  • 購買,若是商品總額大於總資產,提示帳戶餘額不足,不然,購買成功。
  • 附加:可充值、某商品移除購物車
goods = [
    {"name": "電腦", "price": 1999},
    {"name": "鼠標", "price": 10},
    {"name": "遊艇", "price": 20},
    {"name": "手機", "price": 998},
]

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#version:1.1
""" 功能要求: 要求用戶輸入總資產,例如:2000 顯示商品列表,讓用戶根據序號選擇商品,加入購物車 購買,若是商品總額大於總資產,提示帳戶餘額不足,不然,購買成功。 附加:可充值、某商品移除購物車 """ """ 1.建立空的購物車列表 2.要求用戶輸入金額資產 3.輸入後列出商品列表 4.用戶選擇商品,加入購物車 5.結算,若是商品價格大於用戶總資產提示餘額不足,詢問是否刪除商品 6.結算資金充裕,提示購買成功,顯示餘額並退出 """ goods = [ {"name": "電腦", "price": 1999}, {"name": "鼠標", "price": 10}, {"name": "遊艇", "price": 20}, {"name": "手機", "price": 998}, ] cart ={ "goods_list":[], "goods_prices":[] } #用戶輸入帳戶總額 money = int(input("Please enter your assets:")) #列出商品信息 print("Products list:") while True: for key,values in enumerate(goods, 1): for i in range(len(goods)): if key - 1 == i: print(key, goods[i]["name"], goods[i]["price"]) #用戶選擇商品 producets = int(input("You can select the product you like:")) print("Selecting Goods:",goods[producets-1]["name"],"cost:",goods[producets-1]["price"]) #計算選購此商品後餘額 cur_assets = money - goods[producets-1]["price"] if cur_assets > 0: #若是資金充實將商品加入購物車並結算 cart['goods_list'].append(goods[producets-1]["name"]) cart['goods_prices'].append(goods[producets-1]['price']) #print("Your current balance is:", cur_assets, "¥") chose = input("continue,please enter 'c';checked out,enter 'o';show information,enter 'l';quit,enter 'q'") #查看加入購物車商品信息 if chose == 'l': for prod, val in enumerate(cart["goods_list"], 1): print(prod, val) #退出 if chose == "q": print("Thank you") break #繼續購物 if chose == "c": continue #結帳 if chose == "o": total = (sum(cart['goods_prices'])) if total > money: print("Sorry,your account doesn't have a large enough balance") # 不然就退出程序,而且輸出用戶本次消費的狀況 else: print("Thanks,cost:", total, "", "Account balance:", money - total, "") break else: print("error,please try agen") else: print("Sorry,your account doesn't have a large enough balance") break

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#version1.2
goods = [
    {"name": "電腦", "price": 1999},
    {"name": "鼠標", "price": 10},
    {"name": "遊艇", "price": 20},
    {"name": "手機", "price": 998},
]
#用戶輸入總資產
money = input("請輸入總資產:")
asset = int(money)
#定義空購物車
cart = {}
for i in goods:
    print(i["name"],i["price"])
while True:
    i2 = input("請選擇商品(y/Y)結算;")
    #若是選擇結算退出循環
    if i2.lower() == "y":
        break
    #不然繼續購物,
    for item in goods:
        if item["name"] == i2:
            name = item["name"]
            #若是購物車已經有此商品,數量+1
            if name in cart.keys():
                cart[name]["num"] = cart[name]["num"] + 1
            #反之,新增字典
            else:
                cart[name] = {'num': 1,'sigle_price': item["price"]}
    print(cart)
#結帳
all_prices = 0
for k,v in cart.items():
    n = v['sigle_price']
    m = v['num']
    all_sum = n * m
    all_prices = all_prices + all_sum
    if all_prices > asset:
        print("餘額不足")
    else:
        print("消費:",all_prices)

 

 

 

五、用戶交互,顯示省市縣三級聯動的選擇

 

dic = {
    "河北": {
        "石家莊": ["鹿泉", "藁城", "元氏"],
        "邯鄲": ["永年", "涉縣", "磁縣"],
    }
    "河南": {
        ...
    }
    "山西": {
        ...
    }
 
}

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#version:1.1

""" 三級聯動 """ dic = { "河北":{ "石家莊":["鹿泉", "藁城", "元氏"], "邯鄲":["永年", "涉縣", "磁縣"] }, "河南":{ "鄭州":["中原區", "二七區"], "洛陽":["西宮區","洛龍區"] }, "山西":{ "太原":["南城區","北城區"], "大同":["興和","豐鎮"] } } for i in dic: print(i) flag = False for trys in range(3): provinces_name = input("Please select provinces:") if provinces_name in dic: provinces = dic[provinces_name] city = provinces.keys() while True: for citys in city: print(citys) city_name = input("Please enter the city name: ") if city_name in city: area_name = dic[provinces_name][city_name] for i in area_name: print(i) else: print("Please try agen:") continue chose = input("Do you want to quit? quit,enter q;Back to top,enter b.") if chose == "q": print("The application will exits") flag = True break if chose == "b": continue else: print("The information is incorrect,please try agen:") if flag: break else: print("Three times error, the program will exit")

 六.知識點補充

 1.字符串構造

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#字符串構造
d = {"name":"Peter","age":20}
t = "insert into tb(%s) VALUES (%s)"

key_list = []
value_list = []
for k,v in d.items():
    key_list.append(k)
    value_list.append("%%(%s)s" %(k))

print(key_list,",".join(key_list))
print(value_list,','.join(value_list))
sql = t % (','.join(key_list),','.join(value_list))
print(sql)

 2.列表推導式

    大多數Python開發者知道使用列表推導式。你不熟悉這一點? 一個列表推導式是一個創造列表的簡短方式:

>>> some_list = [1, 2, 3, 4, 5]
>>> another_list = [ x + 1 for x in some_list ]
>>> another_list
[2, 3, 4, 5, 6]

  從Python 3.1開始(也反向地移植到了Python 2.7),咱們能夠用一樣的方式建立集合和字典:

>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]
>>> even_set = { x for x in some_list if x % 2 == 0 }
>>> even_set
set([8, 2, 4])

>>> # Dict Comprehensions
>>> d = { x: x % 2 == 0 for x in range(1, 11) }
>>> d
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

第一個例子中,咱們用 some_list 創建了一個元素不重複的集合,但只有偶數。第二個字典的例子中展現了一個字典的建立,這個字典的鍵是1到10(包括10),值是布爾值,指明該鍵是否是一個偶數。

另外一個值得注意的地方是集合的文法,咱們能夠這麼簡單的建立一個集合:

>>>my_set = {1, 2, 1, 2, 3, 4}
>>> my_set
set([1, 2, 3, 4])

3. 使用計數器對象計數

很明顯,但很容易遺忘。計數是一個尋常不過的編程任務,並且大多數情形下這不是個難事。不過計數能夠更簡單。

Python的 collections 庫包含一個 dict 的子類,專門解決計數任務:

>>> from collections import Counter
>>> c = Counter('hello world')
>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})
>>> c.most_common(2)
[('l', 3), ('o', 2)]
相關文章
相關標籤/搜索