werfdsf 发表于 2015-8-27 09:45:20

Python中的元组,列表,字典

元组中的数据不可更改。
通过一个元组访问另外一个元组
>>> a = ("first","second","third")
>>> b = (a,"b's second element")
>>> b
('first', 'second', 'third')
>>> b
'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 ("thefirst and last char is %s and %s" % (some_str,some_str[-1]))
    thefirst 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
('Please', 'slice', 'me')
>>> slice_list=["Please","slice","this","list"]
>>> slice_list
['Please', 'slice']
   如上,使用冒号指定序列中的一个片段指示Python创建了一个新的序列,冒号左侧为旧序列中的元素位置(从0开始),冒号右侧为新序列从旧序列中截取元素的个数。


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']
国外的都被干掉了~.~



页: [1]
查看完整版本: Python中的元组,列表,字典