Python的数组


tuples(元组):

在Python里面,tuples的定义很简单,例如,xy=45,59,然后使用就用xy[0],xy[1]来使用:

__author__="Alex"
__date__ ="$2011-2-17 10:39:27$"
if __name__ == "__main__":
    print "Hello";
xy=45,97
x=xy[0]#set x as  xy[0]
print(x)
y=xy[1]#set y as  xy[1]
print(y)

控制台输出:

Hello
45
97

如何给数组Set值

Python是以索引来区分你给数组赋值的,用append加值进去无论你放进去的是什么类型,int,float,string,甚至是方法,看下面一段代码就知道是怎样赋值的了:

__author__="Alex"
__date__ ="$2011-2-17 10:39:27$"
if __name__ == "__main__":
    print "Hello";
i = [] # create an empty set
k = [ ' hi', 4, 5 ] # create a set with values
print(k)
i.append( 4 ) # append an entry to the set i
print(i)
i.append(5)# append another entry to the set i
print(i)
j = i[0] # j becomes 4
print(j)
print(len( i )) # returns 1, the number of entries of i
print(len( k )) # returns 3
print(k[-1]) # returns 5, the last entry of k

控制台输出:

Hello
[' hi', 4, 5]
[4]
[4, 5]
4
2
3
5

dictionary(字典类型)

Python的字典类型是用关键字来排序的,例如定义numbers = { 'ben': 3, 'tina': 9 } 那么就代表这个字典里面Alex的值为3,而Viki的值为9,然后可以使用Numbers['Alex']来对这个值进行操作。

__author__="Alex"
__date__ ="$2011-2-17 10:39:27$"
if __name__ == "__main__":
    print "Hello";
numbers = { 'Alex': 3, 'Viki': 9 } # creates a dictionary
numbers = dict( Alex=3, Viki=9) # creates the same dictionary with a different syntax
numbers['Alex'] = 'unknown' # change the value of the 'Alex' entry in the dictionary
if numbers['Alex'] == 3:
    print('yes') # using a dictionary in a condition
else:
    print('no')
for n in numbers:
    print( n ) # prints out 'Alex' and on the next line 'Viki'
for n in numbers:
    print( numbers[n] ) # prints out 'unknown' and on the next line 9

输出:

Hello
no
Viki
Alex
9
unknown

相关内容