资讯专栏INFORMATION COLUMN

[Learning Python] Chapter 8 Lists and Dictionaries

gekylin / 251人阅读

摘要:,如何一个方法一使用方法二使用方法方法三使用方法,按升序或降序排列表示升序表示降序和会返回。而仅能删除一个。使用方法可以避免这样的错误导致程序出现。,在中,的方法返回的不再是。不过可以使用强迫它们组成一个。

Chapter 8 Lists and Dictionaries
1, list的concatenation 和 repetition 操作:

>>> [1, 2, 3] + [4, 5, 6] # Concatenation
[1, 2, 3, 4, 5, 6]
>>> ["Ni!"] * 4 # Repetition
["Ni!", "Ni!", "Ni!", "Ni!"]

2,list是mutable sequence,可以做in place assignment.
A, 单一赋值:

>>> L = ["spam", "Spam", "SPAM!"]
>>> L[1] = "eggs" # Index assignment
>>> L
["spam", "eggs", "SPAM!"]

B,用slice给多个item赋值

>>> L[0:2] = ["eat", "more"] # Slice assignment: delete+insert
>>> L # Replaces items 0,1
["eat", "more", "SPAM!"]

虽然[0:2]仅包含2个item,但是,重新赋值的时候可以赋给不止2个,或者少于2个,其实应该这样认识slice assignment:
Step 1:将slice里面的items删除;
Step 2:将要赋值的新的sublist插入。
所以删除的item的个数可以和插入的item的个数不一致。

3,如何extend一个list?
方法一:使用slice assignment:

>>> L
[2, 3, 4, 1]

>>> L[len(L):] = [5, 6, 7] # Insert all at len(L):, an empty slice at end
>>> L
[2, 3, 4, 1, 5, 6, 7]

方法二:使用extend方法

>>> L.extend([8, 9, 10]) # Insert all at end, named method
>>> L
[2, 3, 4, 1, 5, 6, 7, 8, 9, 10]

方法三:使用append方法

>>> L = ["eat", "more", "SPAM!"]
>>> L.append("please") # Append method call: add item at end
>>> L
["eat", "more", "SPAM!", "please"]

4,sort()按升序或降序排列

L = [2, 3, 4, 1]
L.sort()  #表示升序
L
[1, 2, 3, 4]
L.sort(reverse = True) #表示降序
L
[4, 3, 2, 1]

Sort和 append会返回None。所以把他们赋给其他变量,否则那个变量将变为None。

5,有一个sorted函数也可以做这样的事情,并返回一个list:

>>> L = ["abc", "ABD", "aBe"]
>>> sorted([x.lower() for x in L], reverse=True) # Pretransform items: differs!
["abe", "abd", "abc"]

6,reverse可以用来倒序:

>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
>>> list(reversed(L)) # Reversal built-in with a result (iterator)
[1, 2, 3, 4]

7,index, insert, remove, pop, count

>>> L = ["spam", "eggs", "ham"]
>>> L.index("eggs") # Index of an object (search/find)
1
>>> L.insert(1, "toast") # Insert at position
>>> L
["spam", "toast", "eggs", "ham"]
>>> L.remove("eggs") # Delete by value 
>> L
["spam", "toast", "ham"]
>>> L.pop(1) # Delete by position
"toast"
>>> L
["spam", "ham"]
>>> L.count("spam") # Number of occurrences
1

8, del函数不仅可以删除一个item,还可以删除一个section。

>>> L = ["spam", "eggs", "ham", "toast"]
>>> del L[0] # Delete one item
>>> L
["eggs", "ham", "toast"]
>>> del L[1:] # Delete an entire section
>>> L # Same as L[1:] = []
["eggs"]

而remove仅能删除一个item。

9,给某个section赋值一个空List,也就相当于删除该section:L[i:j]=[]

10,dictionary使用key来index:

>>> D = {"spam": 2, "ham": 1, "eggs": 3} # Make a dictionary
>>> D["spam"] # Fetch a value by key
2
>>> D # Order is "scrambled"
{"eggs": 3, "spam": 2, "ham": 1}

11,dictionary的keys方法返回dictionary的所有key 值:

>>> len(D) # Number of entries in dictionary
3
>>> "ham" in D # Key membership test alternative
True
>>> list(D.keys()) # Create a new list of D"s keys
["eggs", "spam", "ham"]

#可以不用list()方法,因为在Python 2.x keys的值本来就是list

12,在dictionary中,给一个key赋值新的value:

>>> D
{"eggs": 3, "spam": 2, "ham": 1}
>>> D["ham"] = ["grill", "bake", "fry"] # Change entry (value=list)
>>> D
{"eggs": 3, "spam": 2, "ham": ["grill", "bake", "fry"]}

13, 删除某个entry,通过key

>>> del D["eggs"] # Delete entry
>>> D
{"spam": 2, "ham": ["grill", "bake", "fry"]}

14,增加一个新的entry:

>>> D["brunch"] = "Bacon" # Add new entry
>>> D
{"brunch": "Bacon", "spam": 2, "ham": ["grill", "bake", "fry"]}

15,dictionary的values()方法返回dictionary的所有values

>>> D = {"spam": 2, "ham": 1, "eggs": 3}
>>> list(D.values()) #可以不用list()方法,因为D.values()的值本来就是list
[3, 2, 1]

16,dictionary的items()方法返回dictionary的所有key=value tuple,返回的是一个list。

>>> list(D.items())
[("eggs", 3), ("spam", 2), ("ham", 1)]

17,有时候不确定dictionary是否有某个key,而如果仍然有之前的index方法来获取,可能引起程序error退出。使用get方法可以避免这样的错误导致程序出现error。
如果没有某个key,get会返回None,而如果不想让程序提示None,可以在第二个参数填入想要输出的内容,如下:

>>> D.get("spam") # A key that is there
2
>>> print(D.get("toast")) # A key that is missing
None
>>> D.get("toast", 88)
88

18,dictionary有一个update方法,可以将一个dictionary加入到另外一个dictionary中,将D2加入到D中。应该注意的是,如果它们有相同的keys,那么D中重复的key所对应的值将被D2的key所对应的值覆盖。

>>> D
{"eggs": 3, "spam": 2, "ham": 1}
>>> D2 = {"toast":4, "muffin":5} # Lots of delicious scrambled order here
>>> D.update(D2)
>>> D
{"eggs": 3, "muffin": 5, "toast": 4, "spam": 2, "ham": 1}

19,dictionary的pop方法,填入的参数是key,返回的值是value,被pop执行的entry被移除出dictionary。

20,如何遍历一个dictionary? 可以用for-in loop:
方法一: for key in D
方法二: for key in D.keys()

21, 如果想要根据value来获得key,可以参考下面的例子:

D = {"spam": 2, "ham": 1, "egg": 3}
E = {"spam": 4, "toast": 3, "hamburger": 5}
D.update(E)
#print D

some_food = [key for (key, value) in D.items() if value == 3]

print some_food

如上面斜体的表达式,将返回list。如果这个value对应多个key,则返回的list将有多个item,如果仅有一个key,那么这个list将只有一个值,此时可以用list[0]来将中括号去除。

22,作为key的值得类型可以是string、integer、float、tuple等不会改变的值, 用户自己定义的object也能作为key,只要它们是hashable并且不会改变的。像list、set、dictionary等这些会变的type不能作为dictionary的key。

23,下面这个例子阐述了tuple类型的key在坐标问题中的作用:

>>> Matrix = {}
>>> Matrix[(2, 3, 4)] = 88
>>> Matrix[(7, 8, 9)] = 99
>>>
>>> X = 2; Y = 3; Z = 4 # ; separates statements: see Chapter 10
>>> Matrix[(X, Y, Z)]
88
>>> Matrix
{(2, 3, 4): 88, (7, 8, 9): 99}

24,创建dictionary的几个方法:
方法一:传统的方法

{"name": "Bob", "age": 40} # Traditional literal expression

方法二:逐一赋值

D = {} # Assign by keys dynamically
D["name"] = "Bob"
D["age"] = 40

方法三:通过dict函数创建,注意,使用这种方法,key只能是string

dict(name="Bob", age=40) # dict keyword argument form

方法四:将key/value作为一个tuple,再用[]括起来,写进dict()中,这种比较少用到

dict([("name", "Bob"), ("age", 40)]) # dict key/value tuples form

方法五:使用zip()函数

dict(zip(keyslist, valueslist)) # Zipped key/value tuples form (ahead)

方法六:使用fromkeys函数,很少用到

>>> dict.fromkeys(["a", "b"], 0)
{"a": 0, "b": 0}

25,使用dictionary comprehensions来创建dictionary的例子:
25.1 别忘了冒号。。

>>> D = {x: x ** 2 for x in [1, 2, 3, 4]} # Or: range(1, 5)
>>> D
{1: 1, 2: 4, 3: 9, 4: 16}

25.2

>>> D = {c: c * 4 for c in "SPAM"} # Loop over any iterable
>>> D
{"S": "SSSS", "P": "PPPP", "A": "AAAA", "M": "MMMM"}

25.3

>>> D = {c.lower(): c + "!" for c in ["SPAM", "EGGS", "HAM"]}
>>> D
{"eggs": "EGGS!", "spam": "SPAM!", "ham": "HAM!"}

25.4

>>> D = {k:0 for k in ["a", "b", "c"]} # Same, but with a comprehension
>>> D
{"b": 0, "c": 0, "a": 0}

26,在Python 3.x中,dictionary的keys()方法返回的不再是list。而是类似像set一样的结构。不过可以使用list()强迫它们组成一个list。

>>> D = dict(a=1, b=2, c=3)
>>> D
{"b": 2, "c": 3, "a": 1}
>>> K = D.keys() # Makes a view object in 3.X, not a list
>>> K
dict_keys(["b", "c", "a"])
>>> list(K) # Force a real list in 3.X if needed
["b", "c", "a"]

它们具有交集、并集、等set所具有的运算:

>>> D = {"a": 1, "b": 2, "c": 3}
>>> D.keys() & D.keys() # Intersect keys views
{"b", "c", "a"}
>>> D.keys() & {"b"} # Intersect keys and set
{"b"}
>>> D.keys() & {"b": 1} # Intersect keys and dict
{"b"}

27,练习题:用两种方法创建一个list,这个list包含5个0:
方法一:
[0,0,0,0,0]
方法二:
[0 for i in range(5)]
方法三:
[0] * 5
方法四:
用循环加append的方法

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/38326.html

相关文章

  • [Learning Python] Chapter 4. Introducing Python Ob

    摘要:可以连接,可以重复可以将两个连接在一起可以重复任意次数如中,号作用于表示连接,而作用于数字表示加法,操作符的作用会根据其作用的对象而有所适应。中的对象被分类为和。针对的核心类型,数字字符串和都是的。 1, >>> len(str(3)) 结果是1,len不能对数字求值,需要先将数字转换为str 2, math模块中,有许多工具可以用来计算数学问题。使用math模块,先导入math: i...

    CHENGKANG 评论0 收藏0
  • Awesome Python II

    摘要: Caching Libraries for caching data. Beaker - A library for caching and sessions for use with web applications and stand-alone Python scripts and applications. dogpile.cache - dogpile.cache...

    lx1036 评论0 收藏0
  • 8步从Python白板到专家,从基础到深度学习

    摘要:去吧,参加一个在上正在举办的实时比赛吧试试你所学到的全部知识微软雅黑深度学习终于看到这个,兴奋吧现在,你已经学到了绝大多数关于机器学习的技术,是时候试试深度学习了。微软雅黑对于深度学习,我也是个新手,就请把这些建议当作参考吧。 如果你想做一个数据科学家,或者作为一个数据科学家你想扩展自己的工具和知识库,那么,你来对地方了。这篇文章的目的,是给刚开始使用Python进行数据分析的人,指明一条全...

    Zachary 评论0 收藏0
  • [Learning Python] Chapter 6: The Dynamic Typing In

    摘要:,可以对对象进行自动地回收。如下,这种情况的发生表示随改变了,应该意识到这个问题。代表引用相同则返回,否则,返回。这个判断会更加严格。的值为的两个量,其必定也是。,和指向了不同的。,由于会存储一些小的和小的以方便重新利用。 1, 在Python中,类型永远跟随object,而非variable。Variable没有类型。 2,在下面的三个式子中,a首先被赋予整形3,再被赋予字符串‘sp...

    lily_wang 评论0 收藏0
  • [Learning Python] Chapter 7 String Fundamentals

    摘要:此时不要在这里面的右边加入,否则会被当做。,这个式子可以将二进制数,转换为十进制的。需要注意的是,需要加上,表示。下面,表示括号内的第一个参数,表示第二个参数。 1, 字符串的连接concatenate有两种方式:A:直接写在一起: >>> title = Meaning of Life # Implicit concatenation >>> title Meaning of L...

    baoxl 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<