#元组(tuple)
-------------------tuple_create.py----------------------
#!/usr/bin/python
# -*- coding: UTF-8 -*-

tuple = ("apple", "banana", "grape", "orange")
#tuple[0] = "a"
t = ("apple",)
t = ()
print tuple[-1]
print tuple[-2]
#print t[0]
-------------------tuple_use.py----------------------
#!/usr/bin/python
# -*- coding: UTF-8 -*-

tuple = ("apple", "banana", "grape", "orange")
print tuple[-1]
print tuple[-2]
tuple2 = tuple[1:3]
tuple3 = tuple[0:-2]
tuple4 = tuple[2:-2]
print tuple2
print tuple3
print tuple4

fruit1 = ("apple", "banana")
fruit2 = ("grape", "orange")
tuple = (fruit1, fruit2)
print tuple
print "tuple[0][1] =",tuple[0][1]
print "tuple[1][1] =",tuple[1][1]
#print tuple[1][2]

#打包
tuple = ("apple", "banana", "grape", "orange")
#解包
a, b, c, d = tuple
print a, b, c, d
-------------------tuple_loop.py----------------------
#!/usr/bin/python
# -*- coding: UTF-8 -*-

#使用range()循环遍历
tuple = (("apple", "banana"),("grape", "orange"),("watermelon",),("grapefruit",))
for i in range(len(tuple)):
    print "tuple[%d] :" % i, "" ,
    for j in range(len(tuple[i])):
        print tuple[i][j], "" ,
    print

#使用map()循环遍历
k = 0
for a in map(None,tuple):
    print "tuple[%d] :" % k, "" ,
    for x in a:
        print x, "" , 
    print
    k += 1
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐