元组中的数据不可更改。
通过一个元组访问另外一个元组
>>> a = ("first","second","third")
>>> b = (a,"b‘s second element")
>>> b[0]
(‘first‘, ‘second‘, ‘third‘)
>>> b[0][1]
‘second‘
列表中的数据可以更改,也可以追加,如下:
>>>breakfast = ["Coffee","Tee","Coca Cola"]
>>>breakfast.append("Juice") #只追加一个element
>>>breakfast.extend(["milk","sprit"]) #追加多个element
字典
创建字典的两种方式:
>>>dic_list={}#创建一个空的字典
>>>dic_list["key1"]="value1" #向字典中赋值
>>>dic_list["key2"]="value2"
或者:
>>>dic_list={"key1":"value1","key2":"value2"}
获取字典中的键:
>>>Keys=dic_list.keys()
>>>print (list(Keys))
[‘key1‘,‘key2‘]
获取字典中的值:
>>>Values=dic_list.values()
>>>print (list(Values))
[‘value1‘,‘value2‘]
在字典中,值可能相同,但是键不能相同,键是唯一存在的。当有键重复时会发生什么呢?
>>>dic_list={"key1":"value1","key1":"value2","key2":"value3"}
>>>print (dic_list.keys())
[‘key1‘,‘key3‘]
>>>print (dic_list["key1"])
value2
可以看到,如果有相同名称的键,后一个会替换掉前一个键的值。
Python可以将字符串当作单个字符的列表那样处理。
例如:
>>>some_str="this is a test!"
>>>print ("the first and last char is %s and %s" % (some_str[0],some_str[-1]))
the first and last char is t and !
序列的其他共有属性
1.引用最后一个元素
>>> tuple_list=("a","b","c")
>>> tuple_list[-1]
‘c‘
>>> list=["a","b","c"]
>>> list[-1]
‘c‘
2.序列的范围
>>> slice_me=("Please","slice","me","!")
>>> slice_me[0:3]
(‘Please‘, ‘slice‘, ‘me‘)
>>> slice_list=["Please","slice","this","list"]
>>> slice_list[0:2]
[‘Please‘, ‘slice‘]
3.通过附加序列增长列表
不能使用append方法将一个序列附加到一个序列的末端,这样的结果是向列表中增加了一个分成的列表。如下:
>>> tuple_str = ("This","is","a","tuple")
>>> list = []
>>> list.append(tuple_str)
>>> list
[(‘This‘, ‘is‘, ‘a‘, ‘tuple‘)]
如果需要根据元组的内容创建一个新的列表,可以使用extend方法,将元祖中的元素插入到列表中
>>> tuple_str = ("This","is","a","tuple")
>>> list = []
>>> list.extend(tuple_str)
>>> list
[‘This‘, ‘is‘, ‘a‘, ‘tuple‘]
4.处理集合(删除重复的元素)
>>> Company = ["Baidu","Ali","Sina","Baidu","Tencent","Sina"]
>>> set(Company)
{‘Sina‘, ‘Tencent‘, ‘Baidu‘, ‘Ali‘}
5.弹出列表中的元素
可以使用pop在处理完列表中的一个元素后将他从列表中删除,当删除引用后,它原来在列表中占据的位置会填上后续元素。
>>> list= ["Baidu","Goole","Cisco","Ali","Tencent","Sina"]
>>> list.pop(1)
‘Goole‘
>>> list.pop(1)
‘Cisco‘
>>>list
[‘Baidu‘, ‘Ali‘, ‘Tencent‘, ‘Sina‘]
国外的都被干掉了~.~