首页 > 代码库 > python tuple、list相关
python tuple、list相关
#python list
‘‘‘
创建list有很多方法:
1.使用一对方括号创建一个空的list:[]
2.使用一对方括号,用‘,‘隔开里面的元素:[a, b, c], [a]
3.Using a list comprehension:[x for x in iterable]
4.Using the type constructor:list() or list(iterable)
‘‘‘ def create_empty_list(): ‘‘‘Using a pair of square brackets to denote the empty list: [].‘‘‘ return [] def create_common_list(): ‘‘‘Using square brackets, separating items with commas: [a], [a, b, c].‘‘‘ return [‘a‘, ‘b‘, ‘c‘, 1, 3, 5] def create_common_list2(): ‘‘‘Using a list comprehension: [x for x in iterable].‘‘‘ return [x for x in range(1, 10)] def str_to_list(s): ‘‘‘Using a string to convert list‘‘‘ if s != None: return list(s) else: return [] def main(): test_listA = create_empty_list() print(test_listA) print(‘#‘ * 50) test_listB = create_common_list() print(test_listB) print(‘#‘ * 50) test_listC = create_common_list2() print(test_listC) print(‘#‘ * 50) test_str = ‘i want to talk about this problem!‘ test_listD = str_to_list(test_str) print(test_listD) if __name__ == ‘__main__‘: main()
2、tuple 转 list
#!/usr/bin/env python # -*- coding:utf-8 -*- aTuple=(12,3,‘a‘,‘yy‘) aList=list(aTuple) print "aTyple type is: ",type(aTuple) print "aList type is: ",type(aList) print "aList‘s value is: ",aList
运行结果
[root@localhost 20170120]# python tuple2list.py aTyple type is: <type ‘tuple‘> aList type is: <type ‘list‘> aList‘s value is: [12, 3, ‘a‘, ‘yy‘]
3、tuple与list相似,但是tuple不能修改,tuple使用小括号,列表用方括号
tuple创建,只需在括号中添加元素,并使用逗号隔开即可
tuple创建只包含一个元素时,需在元素后面添加逗号
tup1=(50,)
1 >>> tup1 = ("all") 2 >>> print tup1 3 all 4 输出字符串 all,这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号。 5 所以,如果元组只有1个元素,就必须加一个逗号,防止被当作括号运算: 6 >>> tup1 = ("all",) 7 >>> print tup1 8 (‘all‘,) 9 >>>
[root@localhost 20170120]# cat tuple.py #!/usr/bin/env python # -*- coding:utf-8 -*- tup1=(‘physics‘,‘chemistry‘,1997,2000); tup2=(1,2,3,4,5,6,7,8,9); print "tup1[0]:",tup1[0]; print "tup2[1:5]:",tup2[1:5]; [root@localhost 20170120]# python tuple.py tup1[0]: physics tup2[1:5]: (2, 3, 4, 5)
修改元组
元组中的元素不能修改,但可以对元组进行连接组合
#代码 #!/usr/bin/env python # -*- coding:utf-8 -*- tup1=(12,34.56) tup2=(‘abc‘,‘xyz‘) tup3=tup1+tup2 print tup3 #运行结果 [root@localhost 20170120]# python tuple.py (12, 34.560000000000002, ‘abc‘, ‘xyz‘)
删除元组
#!/usr/bin/env python # -*- coding:utf-8 -*- tup1=(‘physics‘,‘chemistry‘,1997,2000); print tup1 del tup1 print "After deleting tup1:" print tup1 #执行结果 [root@localhost 20170120]# python tuple.py (‘physics‘, ‘chemistry‘, 1997, 2000) After deleting tup1: Traceback (most recent call last): File "tuple.py", line 8, in <module> print tup1 NameError: name ‘tup1‘ is not defined
python tuple、list相关
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。