python study notes 4

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
# 这里其实还有 > < 符号可以使用

Compared with list use append to add, set use add to add, update to update the entire file

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

Use remove to remove an element and pop to remove the last element

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

The following introduces frozenset, which, as the name suggests, is an immutable set

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

One of the main applications of immutable sets is as a key for dictionaries.

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

Since the sets are not ordered, different orders will not affect the lookup results:

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

This is also the difference between tuples

Some children's shoes think that tuple is also unchanged, and why do I need to use frozenset, because set is not in order, and tuple is in order

Chat 7 control section

Control statements in python all end with:

The tab key of python represents whether you belong to this control statement

if statement

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 statement

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

for statement

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 and break will not be introduced.

Let's say else

ifAs with , the whileand forloop can also be followed by a elsestatement, but it must breakbe used together with and .

  • When the loop ends normally, the loop condition is not satisfied and elseis executed;
  • When the loop is breakterminated , the loop condition is still met and elseis not executed.

The following example

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324611666&siteId=291194637