Set

其实就是无序的、无重复元素的list。它长成这个样子:cast = { "Luigi", "Gumbys", "Spiny" },或者你可以这样:

names = ["Luigi", "Gumbys", "Spiny"]
cast = set(names)

无序的意思是,set没!有!index!再说一遍,set的元素没有编号!元素在set里面就是一坨。而无重复元素的意思就是{ "Luigi", "Luigi", "Gumbys", "Spiny" }这种set是不存在的~set的每一个元素都是独一无二的。因为——第三遍:set没有index!!!所以"Luigi"在cast里面就是"Luigi",没有"Luigi"一世,"Luigi"二世。这就造成了一坨没名字的东东坨在一起没有办法区分彼此,所以必须是独一无二的。不过给set里面元素加名字,变成了dictionary之后就可以了。这是后话~先说对set的操作。

cast = set(["Luigi", "Gumbys", "Spiny"])    # 创造一个集合
len(cast)                    # 长度为3
cast.add("Arthur")               # 添加一个新的集合元素
cast.add("Spiny")                # 再来一个
cast.discard("Arthur")           # 删除元素
cast.discard("The Colonel")    # 删除元素,但该元素不存在,没差~
cast.remove("The Colonel")     # 也是删除,元素同样不存在,但这个会报错
cast.clear()             # 清空

来一组新的继续玩,各国的国旗颜色

canadian = { "Red", "White" }
british = { "Red", "Blue", "White" }
italian = { "Red", "White", "Green" }
if canadian.issubset(british) :
	# if英国国旗颜色包含加拿大的(加拿大国旗颜色是英国的子集)
	print("All Canadian flag colors occur in the British flag.")
if not italian.issubset(british) :
	print("At least one of the colors in the Italian flag does not.")
french = { "Red", "White", "Blue" }
if british == french :        # 两个颜色一样
	print("The British and French flags use the same colors.")
inEither = british.union(italian)
# 求全集,两个国旗包含的全部颜色;输出为 {"Blue", "Green", "White", "Red"}
inBoth = british.intersection(italian))
# 求交集;输出为{"White", "Red"}
print("Colors that are in the Italian flag but not the British:")
print(italian.difference(british))
# 求不同;意大利有的颜色,英国没有的颜色;{'Green'}
british.difference(italian)
# 英国有的颜色,意大利没有的;{"Blue"}

Dictionaries

Dictionary就是有编号的set。不过在这里编号不叫index,叫key。Dictionary长成这样:

contacts = { "Fred": 7235591, "Mary": 3841212, "Bob": 3841212, "Sarah": 2213278 }

:以前的是key,以后的是value。Key的调用和index是一个符号[ ]

len(contacts)            # contacts的长度是4
contacts[“Fred”]        # 7235591
oldContacts = dict(contacts)    # 复制一个dictionary
if "John" in contacts :        # 查找元素
	print("John's number is", contacts["John"])
else :
	print("John is not in my contact list.")
number = str(contacts.get("Fred", 411))
print("Dial " + number)        # 还是查找元素,不过这个有默认值;找不到就打印默认值411
contacts["John"] = 4578102    # 添加一个新的元素
contacts["John"] = 2228102    # 通过key更改这个元素值
contacts.pop("Fred")        # 通过key删除其对应的整个元素

打印关键词

print("My Contacts:")
for key in contacts :
	print(key)

'''输出为:
My Contacts:
Sarah
Bob
John
Mary
Fred'''

打印全部元素(含key和value)

print("My Contacts:")
for key in contacts :
	print("%-10s %d" % (key, contacts[key]))

'''输出为:
My Contacts:
Bob 3841212
Fred 7235591
John 4578102
Mary 3841212
Sarah 2213278'''

顺序打印全部元素

print("My Contacts:")
for key in sorted(contacts) :
	print("%-10s %d" % (key, contacts[key]))
	
'''输出为:
My Contacts:
Bob 3841212
Fred 7235591
John 4578102
Mary 3841212
Sarah 2213278'''

打印元素值

for number in contacts.values() :
	print(number)