美文网首页
python的list和tuple

python的list和tuple

作者: oh_flying | 来源:发表于2017-05-25 19:52 被阅读9次

    说白了,前面的是OC中的可变数组,后面的是不可变数组。

    classmates = ['Michael', 'Bob', 'Tracy']
    

    使用len()获取它的元素个数,相当于OC中的count,还是用下标来取某个值,如:classmates[1]classmates[-1]是取最后一个元素。
    往里面增加元素和swift一样,classmates.append('Adam')classmates.insert(1, 'Jack'),往下标为1的地方插入一个元素。
    要删除list末尾的元素,用pop()方法:

    classmates = ['Michael', 'Bob', 'Tracy']
     classt = classmates.pop()
     print(classmates)
    

    要删除指定位置的元素,用pop(i)方法,其中i是索引位置:

     classmates.pop(1)
    

    替换其他元素:

    classmates[1] = 'Sarah'
    

    里面的数据类型可以不同,和swift一样:

     L = ['Apple', 123, True]
    

    tuple

    tuple就是不可变的数组,定义的时候是这样的:

    a = (1,2,3)
    a = ()//空tuple
    

    但是,要定义一个只有1个元素的tuple,如果你这么定义:

      t = (1)
    

    定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1
    所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:

    t = (1,)

    相关文章

      网友评论

          本文标题:python的list和tuple

          本文链接:https://www.haomeiwen.com/subject/vtbzxxtx.html