Python 字典
字典/键值对集合/关联数组/映射/散列表
字典以什么顺序存储并不重要。重要的是解释器能够快速地访问与一个键关联的值。好消息是解释器确实可以做到这一点,这要归功于字典使用了高度优化的散列算法。
"""
01:Python中无 “++”与“--”功能
"""
>>> person = {'Name':'theName','Gender':'Male','Occupation':'Researcher','Home':'Saven'}
>>> person['Name'] = 'newName'
>>> person
{'Gender': 'Male', 'Home': 'Saven', 'Name': 'newName', 'Occupation': 'Researcher'}
编写一程序用于记录单词中元音字母出现的次数
>>> found = {}
>>> found['a'] = 0
>>> found['e'] = 0
>>> found['i'] = 0
>>> found['o'] = 0
>>> found['u'] = 0
>>> found
# Python中无++功能
>>> found['a']++
File "
found['a']++
^
SyntaxError: invalid syntax
>>>
# +=运算
>>> found['a']+=1
>>> found
{'a': 1, 'i': 0, 'e': 0, 'u': 0, 'o': 0}
# 遍历字典中的keys
>>> for kv in found: # for kv in found:默认遍历字典的keys
... print(kv)
...
a
i
e
u
o
>>>
>>> for kv in found.keys():
... print(kv)
...
a
i
e
u
o
>>>
# 遍历字典中的values
>>> for kv in found.values():
... print(kv)
...
1
0
0
0
0
>>>
# 同时遍历key和value
>>> for k,v in found.items():
... print('key: ' + str(k) + ' value: ' + str(v))
...
key: a value: 1
key: i value: 0
key: e value: 0
key: u value: 0
key: o value: 0
>>>
# 按顺序遍历
>>> for k in sorted(found):
... print('key: ' + str(k) + ' value: ' + str(found[k]))
...
key: a value: 1
key: e value: 0
key: i value: 0
key: o value: 0
key: u value: 0
>>>
# sorted函数会返回一个数据的有序的副本。
# 输入语句中元音字符个数
>>> vowels = ['a','e','i','o','u']
# python2时下面的input函数与phython3不同
# word = input("Provide a word to search for vowels: ")
>>> word = 'iqucbnniuscdbniozSUdbvgcyreivszyuv'
>>> found = {}
>>> found['a'] = 0
>>> found['e'] = 0
>>> found['i'] = 0
>>> found['o'] = 0
>>> found['u'] = 0
>>> for letter in word:
... if letter in vowels:
... found[letter] += 1
...
>>> for k,v in sorted(found.items()):
... print(k,'was found',v,'time(s).')
...
('a', 'was found', 0, 'time(s).')
('e', 'was found', 1, 'time(s).')
('i', 'was found', 4, 'time(s).')
('o', 'was found', 1, 'time(s).')
('u', 'was found', 3, 'time(s).')
>>>
# OC 中for循环与Python中for循环对比。
- (NSArray*)testArryOne {
NSLog(@"testArryOne");
return @[@"1",@"2",@"3"];
}
- (NSArray*)testArryTwo {
NSLog(@"testArryTwo");
return @[@"one",@"two",@"three"];
}
for (NSString *str in [self testArryOne]) {
NSLog(@"For In:%@.",str);
}
/*
testArryOne
For In:1.
For In:2.
For In:3.
*/
for (int i=0; i<[self testArryTwo].count; i++) {
NSLog(@"I < Count:%@",[self testArryTwo][i]);
}
/*
testArryTwo
testArryTwo
I < Count:one
testArryTwo
testArryTwo
I < Count:two
testArryTwo
testArryTwo
I < Count:three
testArryTwo
*/
# Phython中for 循环
>>> def arryOne():
... print("arryOne()")
... return ['1,','2','3','4']
...
>>> def arryTwo():
... print("arryTwo()")
... return ["One","Two","Three","Four"]
...
>>> for str in arryOne():
... print(str)
...
arryOne()
1,
2
3
4
>>> i=0
>>> while i < len(arryTwo()):
... print(arryTwo()[i])
... i += 1
...
arryTwo()
arryTwo()
One
arryTwo()
arryTwo()
Two
arryTwo()
arryTwo()
Three
arryTwo()
arryTwo()
Four
arryTwo()
>>>
观察发现Python中的for循环与OC中的for循环类似:
猜测两者for in 循环使用的都是迭代器模式。
>>> found
{'a': 0, 'i': 4, 'e': 1, 'u': 3, 'o': 1}
>>> found[1]
Traceback (most recent call last):
File "
KeyError: 1
>>>
如果试图访问一个不存在的键的关联值就会产生错误。
# 判断一个元素是否在数组中
>>> 'a' in found.keys()
True
>>>
# True和False时Python提供的常量。
# Phython提供对的三元运算符
>>> y = 10
>>> x = 10 if y>3 else 20
>>> x
10
>>> y = 1
>>> x = 10 if y>3 else 20
>>> x
20
>>>
# xxx = x if yyy else y
# 如果yyy成立,则xxx = x 否则 xxx = y;
# 由于提取字典中不存在的键值对会残生运行时错误,因此要先进行初始化,以下是三种写法:
#写法1
if ‘bananas’ in fruits:
fruits['bananas'] += 1 # 如果已经存在则添加计数
else:
fruits['bananas'] = 1 # 如果没有则初始化为1;
#写法2:利用not in
if ‘pears’ not in fruits:
fruits['pears'] = 0
fruits['pears'] += 1
# 写法3:利用Python自带函数
fruits.setdefault('pear',0)
fruits['pear'] += 1
# 元音字符计数程序版本2:
>>> found = {}
>>> vowels = list('aeiou')
>>> word = 'auvnaifudvb niusvn iqweurhfiquwefpwvcuahpvusvui u'
>>> for w in word:
... if w in vowels:
... if w not in found:
... found[w] = 0
... found[w] += 1
...
>>> found
{'a': 3, 'i': 5, 'u': 9, 'e': 2}
>>>
集合
# 集合与字典类似,使用大括号表示,但集合中各个元素使用逗号分隔,集合中各个元素不重复。
>>> set1 = {1,2,3,4,1,2,3,4}
>>> set1
set([1, 2, 3, 4])
>>> set2 = {}
>>> set2
{} # 其实这是一个字典
>>> set3 = set()
>>> set3
set([]) # 由于大括号表示为字典,所以空集合使用set([])表示
>>>
# 可以用sorted对字典排序,用in判断某元素是否包含在字典中
>>> set0 = set('uwibfiuaebviuadfbviu12312')
>>> set0
set(['a', 'b', 'e', 'd', 'f', 'i', '1', '3', '2', 'u', 'w', 'v'])
>>> 1 in set0
False
>>> '1' in set0
True
>>> sorted(set0)
['1', '2', '3', 'a', 'b', 'd', 'e', 'f', 'i', 'u', 'v', 'w']
#union取并集
>>> set0 = set('123456789')
>>> set1 = set('abcdefghi')
>>> set3 = set0.union(set1)
>>> set3
set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', '1', '3', '2', '5', '4', '7', '6', '9', '8'])
>>> sorted(set3)
['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>>
# 取存在于集合A,且不存在于集合B中的元素;以及两个集合中共有的元素
>>> set0 = set('abc1234567')
>>> set1 = set('abcdfeghij')
>>> set0.difference(set1)
set(['1', '3', '2', '5', '4', '7', '6'])
>>> set1.difference(set0)
set(['e', 'd', 'g', 'f', 'i', 'h', 'j'])
>>>
>>> set0.intersection(set1)
set(['a', 'c', 'b'])
>>> set1.intersection(set0)
set(['a', 'c', 'b'])
>>>
# 利用集合实现获取word中出现的元音字符的功能
>>> word = "dfvbvbiausdbvcsdivbczxjvb";
>>> setOne = set(word).intersection(set("aeiou"))
>>> print(setOne)
set(['a', 'i', 'u'])
>>>
元组、列表
元组:使用小括号包围:不能更改,但指向元组的数据可以更改指向。
>>> tuple1 = (1,2,3)
>>> tuple1
(1, 2, 3)
>>> tuple1[0]
1
>>> tuple1[0]=2
Traceback (most recent call last):
File "
TypeError: 'tuple' object does not support item assignment
>>>
>>> tuple1 = ('a','b','c')
>>> tuple1
('a', 'b', 'c')
>>>
# 获取变量类型 type函数
>>> type(1)
>>> type('1')
>>> type(())
>>> type([])
>>> type({})
>>> type(set())
>>> type({1})
>>> set()
set([]) # 空字典表示为{},空集合就无法使用{}表示
# 注意只有一个对象的元组
>>> type(([])) # 此时解释器没有吧 ([]) 理解为包含一个空数组的元组
>>> type((1))
>>> type((1,)) # 在1后面添加一个逗号,则解释器将其解释为元组。
>>> type(([1]))
>>> type(())
>>> type(([1],))
# 美观打印
>>> listTest = [{"set":{"set1","set2","set3"}},{"a","b","c","d",1234},{"list":[],"set":{"a","b"}},{}]
>>> import pprint
>>> pprint.pprint(listTest)
[{'set': set(['set1', 'set2', 'set3'])},
set([1234, 'a', 'b', 'c', 'd']),
{'list': [], 'set': set(['a', 'b'])},
{}]
>>>
#注意下面,unhashable type不能添加到集合中
>>> list = [1,2,3,4,{"num":[1,2,3]}]
>>> list
[1, 2, 3, 4, {'num': [1, 2, 3]}]
>>> {"a","b","c","d",list}
Traceback (most recent call last):
File "
TypeError: unhashable type: 'list'
>>>
# 以上如字典、集合、列表、元组等出了元组,其他各个数据结构都可以根据需要扩充和收缩,由
# Python解释器负责为你完成内存分配/撤销的有关细节
# set的增删改
>>> setOne
set(['a', 'f', 'u', 'd', 'v'])
>>> setOne.add("python")
>>> setOne
set(['a', 'd', 'f', 'python', 'u', 'v'])
>>> setOne.update("abcdef")
>>> setOne
set(['a', 'c', 'b', 'e', 'd', 'f', 'python', 'u', 'v'])
>>> setOne.remove('a')
>>> setOne
set(['c', 'b', 'e', 'd', 'f', 'python', 'u', 'v'])
>>>
python 2:
>>> setOne
set(['c', 'b', 'e', 'd', 'f', 'python', 'u', 'v'])
>>> setTwo = set("abcdef")
>>> setTwo
set(['a', 'c', 'b', 'e', 'd', 'f'])
>>> setOne & setTwo
set(['c', 'b', 'e', 'd', 'f'])
>>> setOne | setTwo
set(['a', 'c', 'b', 'e', 'd', 'f', 'python', 'u', 'v'])
>>> setOne - setTwo
set(['python', 'u', 'v'])
>>>
>>> setOne.union(setTwo)
set(['a', 'c', 'b', 'e', 'd', 'f', 'python', 'u', 'v'])
>>> setOne.interSection(setTwo)
Traceback (most recent call last):
File "
AttributeError: 'set' object has no attribute 'interSection'
>>> setOne.intersection(setTwo)
set(['c', 'b', 'e', 'd', 'f'])
>>> setOne.difference(setTwo)
set(['python', 'u', 'v'])
>>>
# 在Python中重用代码,以函数为始,也以函数为终。
去几行代码,为他们指定一个名字,就得到一个函数。
取一组函数,把他们打包成一个文件,你就得到一个模块(也可以重用)。