python中list函数和se函数t的区别


本文摘自php中文网,作者尚,侵删。

list字面意思就是一个集合,在Python中List中的元素用中括号[]来表示,可以这样定义一个List:

1

L = [12, 'China', 19.998]

Python中的List是有序的,所以要访问List的话显然要通过序号来访问,就像是数组的下标一样,一样是下标从0开始:

1

2

>>> print L[0]

12

List也可以倒序访问,通过“倒数第x个”这样的下标来表示序号,比如-1这个下标就表示倒数第一个元素:

1

2

3

>>> L = [12, 'China', 19.998]

>>> print L[-1]

19.998

List通过内置的append()方法来添加到尾部,通过insert()方法添加到指定位置(下标从0开始):

1

2

3

4

5

6

7

8

>>> L = [12, 'China', 19.998]

>>> L.append('Jack')

>>> print L

[12, 'China', 19.998, 'Jack']

>>> L.insert(1, 3.14)

>>> print L

[12, 3.14, 'China', 19.998, 'Jack']

>>>

2、 set也是一组数,无序,内容又不能重复,通过调用set()方法创建:

1

>>> s = set(['A', 'B', 'C'])

对于访问一个set的意义就仅仅在于查看某个元素是否在这个集合里面,注意大小写敏感:

1

2

3

>>> print 'A' in s

True>>> print 'D' in s

False

也通过for来遍历:

1

2

3

4

5

6

7

8

9

s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])

 

for x in s:

    print x[0],':',x[1]

 

>>>

Lisa : 85

Adam : 95

Bart : 59

通过add和remove来添加、删除元素(保持不重复),添加元素时,用set的add()方法

1

2

3

4

>>> s = set([1, 2, 3])

>>> s.add(4)

>>> print s

set([1, 2, 3, 4])

如果添加的元素已经存在于set中,add()不会报错,但是不会加进去了:

1

2

3

4

>>> s = set([1, 2, 3])

>>> s.add(3)

>>> print s

set([1, 2, 3])

删除set中的元素时,用set的remove()方法:

1

2

3

>>> s = set([1, 2, 3, 4])

>>> s.remove(4)

>>> print sset([1, 2, 3])

如果删除的元素不存在set中,remove()会报错:

1

2

3

4

5

>>> s = set([1, 2, 3])

>>> s.remove(4)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>K

eyError: 4

所以如果我们要判断一个元素是否在一些不同的条件内符合,用set是最好的选择,下面例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',])

x1 = 'Feb'

x2 = 'Sun'

if x1 in months:

    print 'x1: ok'

else:

    print 'x1: error'

if x2 in months:

    print 'x2: ok'

else:

    print 'x2: error'

>>>

x1: ok

x2: error

更多Python相关技术文章,请访问Python教程栏目进行学习!

以上就是python中list函数和se函数t的区别的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中flask蓝图的使用方法(附代码)

Python开发tornado网站之requesthandler:输出相应函数

实例讲解golang模拟实现带超时的信号量

什么是Python变量?浅谈Python变量中的变量赋值

Python如何合并两个列表?

django中static_root和static_url及staticfiles_dirs浅析

字典里添加元素有哪些方法

Python怎么合并两个列表

lintcode题目记录4

Python序列基础--元组

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...