1.1 元组

#!/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]
>>> 
orange
grape
apple
>>> 
#!/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
>>> 
orange
grape
('banana', 'grape')
('apple', 'banana')
()
(('apple', 'banana'), ('grape', 'orange'))
tuple[0][1] = banana
tuple[1][1] = orange
apple banana grape orange
>>> 
#!/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
print '\n'
#使用map()循环遍历
k = 0
for a in map(None,tuple):
    print "tuple[%d] :" % k, "" ,
    for x in a:
        print x, "" , 
    print
    k += 1
以上相当于输出二维数组
>>> 
tuple[0] :  apple  banana 
tuple[1] :  grape  orange 
tuple[2] :  watermelon 
tuple[3] :  grapefruit 


tuple[0] :  apple  banana 
tuple[1] :  grape  orange 
tuple[2] :  watermelon 
tuple[3] :  grapefruit 
>>> 
1.2 列表
#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = ["apple", "banana", "grape", "orange"]
print list
print list[2]
list.append("watermelon")
list.insert(1, "grapefruit")
print list
list.remove("grape")
print list
#list.remove("a")
print list.pop()
print list

list = ["apple", "banana", "grape", "orange"]
print list[-2]
print list[1:3]
print list[-3:-1]
list = [["apple", "banana"],["grape", "orange"],["watermelon"],["grapefruit"]] #遍历,类似于元组
for i in range(len(list)):
    print "list[%d] :" % i, "" ,
    for j in range(len(list[i])):
        print list[i][j], "" ,
    print
>>> 
['apple', 'banana', 'grape', 'orange']
grape
['apple', 'grapefruit', 'banana', 'grape', 'orange', 'watermelon']
['apple', 'grapefruit', 'banana', 'orange', 'watermelon']
watermelon
['apple', 'grapefruit', 'banana', 'orange']
grape
['banana', 'grape']
['banana', 'grape']
list[0] :  apple  banana 
list[1] :  grape  orange 
list[2] :  watermelon 
list[3] :  grapefruit 
>>> 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = ["grape", "grape"]
list2 = ["apple", list, "orange"]             
print list
print list2

list3=[i for i in list if i not in list2]
print list3

>>> 
['grape', 'grape']
['apple', ['grape', 'grape'], 'orange']
['grape', 'grape'] 
>>> 
#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = ["grape", "apple"]
list2 = ["apple", list, "orange"]             
print list
print list2

list3=[i for i in list if i not in list2]    # 在list中却不在list2中的元素
print list3
>>> 
['grape', 'apple']
['apple', ['grape', 'apple'], 'orange']
['grape']
>>> 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = ["apple", "grape", "grape", "orange"]
list.remove("grape")
print list

list = ["apple", "banana", "grape", "orange"]
print list.index("grape")
print list.index("orange")
print "orange" in list

list1 = ["apple", "banana"]
list2 = ["grape", "orange"]
list1.extend(list2)
print list1
list3 = ["watermelon"]
list1 = list1 + list3
print list1
list1 += ["grapefruit"]
print list1
list1 = ["apple", "banana"] * 2
print list1

#使用列表的sort方法排序
list = ["banana", "apple", "orange", "grape"]
list.sort()
print "Sorted list:", list
list.reverse()
print "Reversed list:", list

#使用函数sorted排序,返回一个新的列表
list = ["banana", "apple", "orange", "grape"]
for li in sorted(set(list)):
    print li, "" ,

>>> 
['apple', 'grape', 'orange']
2
3
True
['apple', 'banana', 'grape', 'orange']
['apple', 'banana', 'grape', 'orange', 'watermelon']
['apple', 'banana', 'grape', 'orange', 'watermelon', 'grapefruit']
['apple', 'banana', 'apple', 'banana']
Sorted list: ['apple', 'banana', 'grape', 'orange']
Reversed list: ['orange', 'grape', 'banana', 'apple']
apple  banana  grape  orange 
>>> 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#堆栈的实现
list = ["apple", "banana", "grape"]
list.append("orange")
print list
print "弹出的元素:", list.pop()
print list

#队列的实现
list = ["apple", "banana", "grape"]
list.append("orange")
print list
print "弹出的元素:", list.pop(0)
print list

>>> 
['apple', 'banana', 'grape', 'orange']
弹出的元素: orange
['apple', 'banana', 'grape']
['apple', 'banana', 'grape', 'orange']
弹出的元素: apple
['banana', 'grape', 'orange']
>>> 

注意:

list也有深拷贝和浅拷贝,

>>> import copy
>>> t = a
>>> t
[1, 2, [100, 4, 5]]
>>> t = a[:]
>>> t
[1, 2, [100, 4, 5]]
>>> t[2][0] = 1
>>> t
[1, 2, [1, 4, 5]]
>>> a
[1, 2, [1, 4, 5]]#简单的复制,通过赋值方式,一个改变都改变
>>> a[2][0] = 0
>>> a
[1, 2, [0, 4, 5]]
>>> t
[1, 2, [0, 4, 5]]
>>> a1 = copy.copy(b)#使用copy,可以保持独立b变,a1不变
>>> b
[1, 2, [3, 4, 9]]
>>> a1
[1, 2, [3, 4, 9]]
>>> a[2][0] = 8
>>> a
[1, 2, [8, 4, 5]]
>>> b
[1, 2, [3, 4, 9]]
>>> a1
[1, 2, [3, 4, 9]]
>>> b[0] = 0
>>> b
[0, 2, [3, 4, 9]]
>>> a1
[1, 2, [3, 4, 9]]#使用copy,可以保持独立b变,a1不变
>>> a1 = copy.deepcopy(b)
>>> a1
[0, 2, [3, 4, 9]]
>>> b
[0, 2, [3, 4, 9]]
>>> b[0] = 1000#使用copy,可以保持独立b变,a1不变
>>> b
[1000, 2, [3, 4, 9]]
>>> a1
[0, 2, [3, 4, 9]]
>>> a1[2][0] = 555
>>> a1
[0, 2, [555, 4, 9]]
>>> b
[1000, 2, [3, 4, 9]]
>>> 
1.浅拷贝:原始对象 与 拷贝后的对象,可能引用的是同一块内存的数据   

可能的后果:改变原始对象(拷贝后的对象),拷贝后的对象(原始对象)也会改变


2.深拷贝:拷贝后的对象,系统为其另外开辟了一块内存,但是数据是相同的,两者互不影响

对数组或字典,逐级进行拷贝,直到本级的下一级是简单的对象(即:不是嵌套的字典或数组)


代码里面加了颜色居然反映不出来,只有以文本形式粘贴了!

1.3 字典
#!/usr/bin/python
# -*- coding: UTF-8 -*-

#使用字母作为索引
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print dict
print dict["a"]
#使用数字作为索引
dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"}
print dict
print dict[2]
#字典的添加、删除
dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"}
del dict[1]
print dict
print dict[2]
#使用元组作为索引
dict = {}
dict[("a","p","p","l","e")] = "apple"
dict[("b","a","n","a","n","a")] = "banana"
print dict
print dict[("a","p","p","l","e")]

print "%s, %(a)s, %(b)s" % {"a":"apple", "b":"banana"}

>>>
{'a': 'apple', 'b': 'banana', 'o': 'orange', 'g': 'grape'}
apple
{1: 'apple', 2: 'banana', 3: 'grape', 4: 'orange'}
banana
{2: 'banana', 3: 'grape', 4: 'orange'}
banana
{('b', 'a', 'n', 'a', 'n', 'a'): 'banana', ('a', 'p', 'p', 'l', 'e'): 'apple'}
apple
{'a': 'apple', 'b': 'banana'}, apple, banana
>>> 


#!/usr/bin/python
# -*- coding: UTF-8 -*-

#字典的添加、删除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon"
del(dict["a"])
dict["g"] = "grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict

#字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
    print "dict[%s] =" % k,dict[k]

#字典items()的使用
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()

#调用items()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
    print "dict[%s] =" % k, v

#调用iteritems()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict.iteritems()
for k, v in dict.iteritems():
    print "dict[%s] =" % k, v
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
    print "dict[%s] =" % k, v
    


#使用列表、字典作为字典的值
dict = {"a" : ("apple",), "bo" : {"b" : "banana", "o" : "orange"}, "g" : ["grape","grapefruit"]}
print dict["a"]
print dict["a"][0]
print dict["bo"]
print dict["bo"]["o"]
print dict["g"]
print dict["g"][1]

>>>
banana
{'w': 'watermelon', 'o': 'orange', 'g': 'grapefruit'}
{}


dict[a] = apple
dict[b] = banana
dict[o] = orange
dict[g] = grape


[('a', 'apple'), ('c', 'grape'), ('b', 'banana'), ('d', 'orange')]


dict[a] = apple
dict[b] = banana
dict[o] = orange
dict[g] = grape


<dictionary-itemiterator object at 0x02000B40>
dict[a] = apple
dict[c] = grape
dict[b] = banana
dict[d] = orange
dict[a] = apple
dict[c] = grape
dict[b] = banana
dict[d] = orange


('apple',)
apple
{'b': 'banana', 'o': 'orange'}
orange
['grape', 'grapefruit']
grapefruit
>>>

#!/usr/bin/python
# -*- coding: UTF-8 -*-

dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#输出key的列表
print dict.keys()
print 'next one \n'
#输出value的列表
print dict.values()
print 'next one \n'
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()

dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
it = dict.iteritems()
print it
print 'next one \n'
#字典中元素的获取方法
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict
print dict.get("c", "apple")         ###没有取到C,则区默认值apple
print dict.get("e", "apple")
print 'next one \n'
#get()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
if "key1" in D:
    print D["key1"]
else:
    print "None"
print 'next one \n'
#字典的更新
dict = {"a" : "apple", "b" : "banana"}
print dict
dict2 = {"c" : "grape", "d" : "orange"}
dict.update(dict2)
print dict
print 'next one \n'
#udpate()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
    D[k] = E[k]
print D
print 'next one \n'
#字典E中含有字典D中的key
D = {"key1" : "value1", "key2" : "value2"}
E = {"key2" : "value3", "key4" : "value4"}
for k in E:
    D[k] = E[k]
print D
print 'next one \n'
#设置默认值
dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict

>>>
['a', 'c', 'b', 'd']
next one

['apple', 'grape', 'banana', 'orange']
next one

[('a', 'apple'), ('c', 'grape'), ('b', 'banana'), ('d', 'orange')]
<dictionary-itemiterator object at 0x01F00B40>
next one

{'a': 'apple', 'c': 'grape', 'b': 'banana', 'd': 'orange'}
grape
apple
next one

value1
next one

{'a': 'apple', 'b': 'banana'}
{'a': 'apple', 'c': 'grape', 'b': 'banana', 'd': 'orange'}
next one

{'key3': 'value3', 'key2': 'value2', 'key1': 'value1', 'key4': 'value4'}
next one

{'key2': 'value3', 'key1': 'value1', 'key4': 'value4'}
next one

{'a': None}
{'a': 'apple'}
Help on class list in module __builtin__:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#调用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print dict
print '\n'
#按照key排序  
print sorted(dict.items(), key=lambda d: d[0])
print '\n'
#按照value排序  
print sorted(dict.items(), key=lambda d: d[1])
print '\n'

#字典的浅拷贝
dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()                #相当于将dict赋值给dict2
print dict2
print '\n'

#字典的深拷贝
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict

>>>
{'a': 'apple', 'c': 'orange', 'b': 'grape', 'd': 'banana'}


[('a', 'apple'), ('b', 'grape'), ('c', 'orange'), ('d', 'banana')]


[('a', 'apple'), ('d', 'banana'), ('b', 'grape'), ('c', 'orange')]


{'a': 'apple', 'b': 'grape'}


{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}
>>>
比较:
#字典的深拷贝
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)
print dict2
dict3 = copy.copy(dict)
print dict3
dict2["b"]["g"] = "orange"
print dict2
print dict
dict3["b"]["g"] = "orange"
print dict3
print dict

>>>
{'a': 'apple', 'b': {'g': 'grape', 'o': 'orange'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}
{'a': 'apple', 'b': {'g': 'orange', 'o': 'orange'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}
>>>
1.浅拷贝:原始对象 与 拷贝后的对象,可能引用的是同一块内存的数据   

可能的后果:改变原始对象(拷贝后的对象),拷贝后的对象(原始对象)也会改变


2.深拷贝:拷贝后的对象,系统为其另外开辟了一块内存,但是数据是相同的,两者互不影响

对数组或字典,逐级进行拷贝,直到本级的下一级是简单的对象(即:不是嵌套的字典或数组)

一个比较好的字典实例:

#/bin/env python
#-*- encoding:UTF-8 -*-

#create a mapping of state to abbreviation 
states = {
        'Oregon': 'OR',
        'Florida': 'FL',
        'California': 'CA',
        'New York': 'NY',
        'Michigan': 'MI'
        }

#create a basic set of states and some cities in them 
cities = {
        'CA': 'San Francisco',
        'MI': 'Detroit',
        'FL': 'Jacksonville',
        }

#add some more cities 
cities ['NY'] = 'New York'
cities ['OR'] = 'Portland'

print "NY State has :", cities ['NY']
print "OR State has :", cities ['OR']

#print some states 
print '-' * 10
print "Michigan's abbreviation is :",states ['Michigan']  #获取字典值的方法,用下标文字
print "Florida's abbreviation is :",states ['Florida']

#do it by using the state then cities dict 
print "-" * 10
print "Michigan's has :",cities [states ['Michigan']]  #获取第二层字典值的方法
print "Florida has :",cities [states ['Florida']]

#print every state abbreviation 
print '-' * 10
for state , abbrev in states.items():           #字典的遍历输出是无序的,以后都是
        print "%s is abbreviated %s " % (state, abbrev)

#print every city in state 
print '-' * 10
for abbrev ,city  in cities.items():
        print "%s has the city %s " % (abbrev, city )

#now do both at the same time
print '-' * 10
for state ,abbrev in states.items():
        print "%s state is abbreviated %s and has city %s " % (state,abbrev ,cities[abbrev])                 #遍历两个相关联字典的方法

print '-' * 10
#safety get a abbreviation  by state that might not be there 
state  = states.get('Texas',None)  #获取某一字典值的方法get

if not state :
        print "sorry , no texas ."

#get a city with a default value 
city = cities.get("TX", "Does Not Exist")  #注意如果无法获取时返回"Does Not Exist"
print "The city for the state 'TX' is : %s " % city

输出:

root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/python# python exe39.py 
----------
NY State has : New York
OR State has : Portland
----------
Michigan's abbreviation is : MI
Florida's abbreviation is : FL
----------
Michigan's has : Detroit
Florida has : Jacksonville
----------
California is abbreviated CA 
Michigan is abbreviated MI 
New York is abbreviated NY 
Florida is abbreviated FL 
Oregon is abbreviated OR 
----------
FL has the city Jacksonville 
CA has the city San Francisco 
MI has the city Detroit 
OR has the city Portland 
NY has the city New York 
----------
California state is abbreviated CA and has city San Francisco 
Michigan state is abbreviated MI and has city Detroit 
New York state is abbreviated NY and has city New York 
Florida state is abbreviated FL and has city Jacksonville 
Oregon state is abbreviated OR and has city Portland 
----------
sorry , no texas .
The city for the state 'TX' is : Does Not Exist 



1.4 序列
#!/usr/bin/python
# -*- coding: UTF-8 -*-

#索引操作
tuple = ("apple", "banana", "grape", "orange")
list = ["apple", "banana", "grape", "orange"]
str = "apple"
print tuple[0]
print tuple[-1]
print list[0]
print list[-1]
print str[0]
print str[-1]

#分片操作
tuple = ("apple", "banana", "grape", "orange")
list = ["apple", "banana", "grape", "orange"]
str = "apple"
print tuple[:3]
print tuple[3:]
print tuple[1:-1]
print tuple[:]
print list[:3]
print list[3:]
print list[1:-1]
print list[:]
print str[:3]
print str[3:]
print str[1:-1]
print str[:]

>>>
apple
orange
apple
orange
a
e
('apple', 'banana', 'grape')
('orange',)
('banana', 'grape')
('apple', 'banana', 'grape', 'orange')
['apple', 'banana', 'grape']
['orange']
['banana', 'grape']
['apple', 'banana', 'grape', 'orange']
app
le
ppl
apple
>>>


模块


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
print sys.modules.keys()
print sys.modules.values()
print sys.modules["os"]

import sys
d = sys.modules.copy()
import copy,string
print zip(set(sys.modules) - set(d))








posted on 2022-07-05 18:13  我在全球村  阅读(23)  评论(0编辑  收藏  举报