元哥3天学Python--Day2

1. Sequential Data Types

Unlike other programming languages Python uses the same syntax and function names to work on sequential data types.

  1. Bytes
  • 0 ~ 255 --> 对应ASCII
  1. Lists
  • Mutable
  • Arbitrary objects
  • Variable Size
[42, "What's the question?", 3.1415]
  1. Tuples
  • Immutable list
  • Faster than list
  • Can be used as keys in dictionaries
t = ("tuples", "are", "immutable")
  1. Slicing
  • s[begin: end]
  • s[begin: end: step]

s[begin], s[begin + 1 * step], ... s[begin + i * step] for all (begin + i * step) < end.

str[0:6]
str[5:]
without_last_five = str[0:-5]
str[:]
str[::3]
  1. Operations
  • contain
"a" not in abc
"x" in str
  • repetition
3 * ["a","b","c"]

pitfall: repetition operator "*4" creates 4 references to the list x

>>> x = ["a","b","c"]
>>> y = [x] * 4
>>> y
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> y[0][0] = "p"
>>> y
[['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c']]
>>>

2. Lists

A list can be seen as a stack.

  • append
  • Return "None"
lst = [3, 5, 7]
lst.append(42) // list == [3, 5, 7, 42]
lst = lst.append(42) // list == None 
  • pop(i)
  • Return and remove 第i个 element
  • Without an argument. The last element will be returned.
cities = ["Hamburg", "Linz", "Salzburg", "Vienna"]
cities.pop(0) // cities == ['Linz', 'Salzburg', 'Vienna']
cities.pop() // cities.pop(-1)
  • extend
  • appending all the elements of an iterable(e.g. list, tuple, string)
lst = ["a", "b", "c"]
programming_language = "Python"
lst.extend(programming_language) // ['a', 'b', 'c', 'P', 'y', 't', 'h', 'o', 'n']
  • '+'
  • 注意:不要用x = x + [...]
L = [3, 4]
// L 为新的对象,具有新的id!千万不要这么用!
L = L + [42] 
// 在原对象的基础上添加,id没变
L += [42]
L.append(42)
L.extend([42])
  • remove
  • remove the first occurrence of an element
  • If not contained, a ValueError will be raised.
colours = ["red", "green", "blue", "green", "yellow"]
colours.remove("green")
  • index

  • s.index(x[, start, end])

  • insert

  • s.insert(index, object)

3. Shallow and Deep Copy

  • Shallow Copy
  • Copy Reference
colours1 = ["red", "blue"]
colours2 = colours1
colours2[1] = "green" // side effect: 两个list都会为['red', 'green']
  • Copy with Slice Operator

    • 对于shallow list(无sublist的list),无side effect

list1 = ['a','b','c','d']
list2 = list1[:]
list2[1] = 'x' // list1 没有变

* 对于非shallow list,有side effect

lst1 = ['a','b',['ab','ba']]
lst2 = lst1[:]
lst2[0] = 'c' //lst1不变
lst2[2][1] = 'd' //lst1改变

* Deep Copy
* 所有元素(包括sublist),都被copy为新的对象

lst2 = deepcopy(lst1)


###4. Dictionaries

> Can use arbitrary types as values in a dictionary, but only immutable data types can be used as keys

dic = { (1,2,3):"abc", 3.1415:"abc"}


1. Operators
 * pop(k) ---> remove (k, v) and return v
 * pop(k, d) ---> if k not contains, return default value d
 * popitem() ---> 无参数,随机remove
 * get(k) ---> if k not contains, return None
 * get(k, d) ---> if k not contains, return default value d
 * copy() ---> shallow copy
 * update() --->用于merge两个dict

knowledge = {"Frank": {"Perl"}, "Monica":{"C","C++"}}
knowledge2 = {"Guido":{"Python"}, "Frank":{"Perl", "Python"}}
knowledge.update(knowledge2) // {'Frank': {'Python', 'Perl'}, 'Guido': {'Python'}, 'Monica': {'C', 'C++'}}

* keys() & values() ---> 遍历

2. List <=> Dict
* Dict -> List
   * (K, V) 被转成tuple

w = {"house":"Haus", "cat":"", "red":"rot"}
items_view = w.items()
items = list(items_view) //[('house', 'Haus'), ('cat', ''), ('red', 'rot')]
keys_view = w.keys()
keys = list(keys_view) //['house', 'cat', 'red']
values_view = w.values()
values = list(values_view) //['Haus', '', 'rot']

  * List -> Dict

dishes = ["pizza", "sauerkraut", "paella", "hamburger"]
countries = ["Italy", "Germany", "Spain", "USA"]
//方法1
country_specialities = list(zip(countries, dishes)) //按位置匹配
country_specialities_dict = dict(country_specialities) //list转换dict
//方法2
country_specialities_zip = zip(dishes,countries) //返回iter
country_specialities_dict = dict(country_specialities_zip) //直接用iter生成dict

> 注意:zip()返回的是iterator,再第一次遍历完之后会自己销毁,不能再第二次使用

###5. Set

1. doesn't allow mutable objects

x = set(["Perl", "Python", "Java"])
adjectives = {"cheap","expensive","inexpensive","economical"}

* sets are mutable

* Frozensets are immutable

cities = frozenset(["Frankfurt", "Basel","Freiburg"])


4. Operations

colours.add("yellow")
cities.clear()
cities_backup = more_cities.copy() // shallow copy
x.difference(y).difference(z)
x - y - z // same as above
x.difference_update(y)
x = x - y // same as above
x.discard("a") //not contains, nothing happen
x.remove("a") //not contains, KeyError
x.intersection(y)
x & y //same as above
x.isdisjoint(y)
x.issubset(y)
x < y //same as above
x.issuperset(y)
x > y //same as above
x.pop() //removes and returns an arbitrary set element

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容