python 列表list初始化

python 列表list初始化

  1. 基本方法

    $ python
    Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> n = [1, 2, 3, 4]
    >>> print (n)
    [1, 2, 3, 4]
    >>> 
  2. 连续数字初始化

    >>> list1 = [n for n in range(1,6)]
    >>> print list1
     File "<stdin>", line 1
       print list1 #python3 特性输出要()
                 ^
    SyntaxError: Missing parentheses in call to 'print'
    >>> print (list1)
    [1, 2, 3, 4, 5]
    >>> 
  3. 相同的值初始化

    >>> #第一种方法
    >>> list2 = ['a' for n in range(4)]
    >>> print(list2)
    ['a', 'a', 'a', 'a']
    >>> #第二种方法:字符和数字
    >>> list3 = ['b'] * 4
    >>> print(list3)
    ['b', 'b', 'b', 'b']
    >>> list4 = [3] * 4
    >>> print (list4)
    [3, 3, 3, 3]
    >>> 
  4. 二位数组初始化

    $ python
    Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> #初始一个5×4的数组
    >>> multilist = [[1 for col in range(5)] for row in range(4)]
    >>> print (multilist)
    [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
    >>> 

    list 练习

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值