python - 简单化list的 For[if] 语句

python的list数据

    >>>a=[1, 2, 3, 4, 5, 6, 7]
    >>>b=a
    >>>b
    [1, 2, 3, 4, 5, 6, 7]

 

用这种方式将a.list的数据传递给b.list时,当b.list 的数据发生改变,会影响到a.list

    >>>a=[1, 2, 3, 4, 5, 6, 7]
    >>>b=a
    >>>b
    [1, 2, 3, 4, 5, 6, 7]


    >>>b[3] = 'c'
    >>>b
    [1, 2, 3, 'c', 5, 6, 7]
    >>>c
    [1, 2, 3, 'c', 5, 6, 7]

 

因此,要想改变b.list的数据而不影响a.list,就需要使用循环的方式将数据从a.list中取出,再append进b.list中

    >>> a = [1, 2, 3, 4, 5, 6, 7]
    >>> b = []
    >>> for i in a:
                b.append(i)

    >>> b
    [1, 2, 3, 4, 5, 6, 7]

    >>> b[3] = 'c'
    >>> b
    [1, 2, 3, 'c', 5, 6, 7]

    >>>a
    [1, 2, 3, 4, 5, 6, 7]

 

这样虽然能够得到想要的list,从代码的书写上却不怎么友好,因此,可以使用 For[if] 的语句替代:

    >>> a = [1, 2, 3, 4, 5, 6, 7]  
    >>> b = [i for i in a] #省略if
    >>> b
    [1, 2, 3, 4, 5, 6, 7]
    >>> a = [1, 2, 3, 4, 5, 6, 7]  
    >>> b = [i for i in a if i % 2 == 0]
    >>> b
    [2, 4, 6]

  # b是从a中选取满足i%2==0的元素组成的Lis

 

 

=============================================================

嵌套 For[if] 语句使用:

    >>> a = [1, 2, 3, 4, 5, 6, 7]
    >>> b = ['x', 'y', 'z']
    >>> newList = [ (i, j) for i in a for j in b ]
    >>> newList
    [(1, 'x'), (1, 'y'), (1, 'z'), (2, 'x'), (2, 'y'), (2, 'z'), (3, 'x'), (3, 'y'), (3, 'z'), (4, 'x'), (4, 'y'), (4, 'z'), (5, 'x'), (5, 'y'), (5, 'z'), (6, 'x'), (6, 'y'), (6, 'z'), (7, 'x'), (7, 'y'), (7, 'z')]


    >>> newList2 = [ (i, j) for i in a for j in b if i%2 == 0 and j<'z' ]
    >>> newList2
    [(2, 'x'), (2, 'y'), (4, 'x'), (4, 'y'), (6, 'x'), (6, 'y')]

 

posted @ 2017-09-19 17:23  blitheG  阅读(1555)  评论(0编辑  收藏  举报