python学习笔记四

Chat 6 set

a = set([1, 2, 3, 1])
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# 创建set
a.union(b)
a | b 
a.intersection(b)
a & b
a.difference(b)
a - b
a.symmetric_difference(b)
a ^ b
a = {1, 2, 3}
b = {1, 2}
b.issubset(a)
b <= a
a.issuperset(b)
a >= b
# 这里其实还有 > < 符号可以使用

相对于list使用append来添加,set使用add来添加,update来更新整个文件

t = {1, 2, 3}
t.add(5)
t.update([5, 6, 7])

使用remove来删除某一个元素,pop来删除最后一个元素

t.remove(1)
t.remove(10)
# 如果不存在这个的话,会报错
t.discard(10)
# 相比 t.remove(), t.discard()的话不会报错
t.pop()

下面介绍下frozenset, 顾名思义就是不变的集合

s = frozenset([1, 2, 3, 'a', 1])

不变集合的一个主要应用是来作为字典的健

flight_distance = {}
city_pair = frozenset(['Los Angeles', 'New York'])
flight_distance[city_pair] = 2498
flight_distance[frozenset(['Austin', 'Los Angeles'])] = 1233
flight_distance[frozenset(['Austin', 'New York'])] = 1515
flight_distance

由于集合不分顺序,所以不同顺序不会影响查阅结果:

flight_distance[frozenset(['New York','Austin'])]
flight_distance[frozenset(['Austin','New York'])]

这个也是tuple的区别

有些童鞋认为tuple也是不变的,而我为什么需要使用frozenset,因为set不分顺序,而tuple是分顺序的

Chat 7 control section

python的控制语句都以:结尾

python的tab键代表了你是否属于这个控制语句当中

if 语句

x = -0.5
if x > 0:
    print "Hey!"
    print "x is positive"
    print "This is still part of the block"
print "This isn't part of the block, and will always print."

year = 1900
if year % 400 == 0:
    print "This is a leap year!"
# 两个条件都满足才执行
elif year % 4 == 0 and year % 100 != 0:
    print "This is a leap year!"
else:
    print "This is not a leap year."

while  语句

plays = set(['Hamlet', 'Macbeth', 'King Lear'])
while plays:
    play = plays.pop()
    print 'Perform', play

for 语句

plays = set(['Hamlet', 'Macbeth', 'King Lear'])
for play in plays:
    print 'Perform', play

total = 0
for i in xrange(100000):
    total += i
print total

# range(x)会在做之前生成一个临时表,这样对于效率,内存是不好的

continue和break就不介绍了吧

下面说下else

if 一样, whilefor 循环后面也可以跟着 else
语句,不过要和break一起连用。

  • 当循环正常结束时,循环条件不满足, else 被执行;
  • 当循环被 break 结束时,循环条件仍然满足, else 不执行。

如下的例子

values = [11, 12, 13, 100]
for x in values:
    if x <= 10:
        print 'Found:', x
        break
else:
    print 'All values greater than 10'

相关文章