前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python: 早点知道这些就不会这样了

Python: 早点知道这些就不会这样了

作者头像
昱良
发布2018-04-04 14:16:28
5730
发布2018-04-04 14:16:28
举报

现在在Python 2的代码中都用import from future来导入Python 3的输出和除法。现在用到的几乎所有库都支持Python 3,因此会很快迁移到Python 3中。

代码语言:javascript
复制
mynumber = 5

print "Python 2:"
print "The number is %d" % (mynumber)
print mynumber / 2,
print mynumber // 2

from __future__ import print_function
from __future__ import division

print("nPython 3:")
print("The number is {}".format(mynumber))
print(mynumber / 2, end=" ")
print(mynumber // 2)

输出:
Python 2:
The number is 5
2 2

Python 3:
The number is 5
2.5 2

enumerate(list)

很明显,迭代列表时,应该同时迭代其中的元素及其索引,但在很长一段时间内,我都尴尬的使用计数变量或切片。

代码语言:javascript
复制
mylist = ["It"s", "only", "a", "model"]

for index, item in enumerate(mylist):
    print(index, item)

输出:
0 It"s
1 only
2 a
3 model

链式比较操作符

由于我以前使用的是静态语言(在这些语言中该用法有二义性),从来没有将两个比较操作符放在一个表达式中。在许多语言中,4 > 3 > 2会返回False,因为4 > 3的结果是布尔值,而True > 2将得出False。

代码语言:javascript
复制
mynumber = 3

if 4 > mynumber > 2:
    print("Chained comparison operators work! n" * 3)

输出:
Chained comparison operators work!
Chained comparison operators work!
Chained comparison operators work!

collections.Counter

Python的集合库看上去是最好的。在计算需要集合中元素的个数时,StackOverflow找到的答案是创建有序字典,但我坚持使用一个代码片段来创建字典,计算结果中元素出现的频率。直到有一天,我发现可以用collections.deque。

代码语言:javascript
复制
from collections import Counter
from random import randrange
import pprint

mycounter = Counter()

for i in range(100):
    random_number = randrange(10)
    mycounter[random_number] += 1

for i in range(10):
    print(i, mycounter[i])

输出:
0 10
1 10
2 13
3 6
4 6
5 11
6 10
7 14
8 12
9 8

字典推导

Python开发者的一个重要标志就是理解列表推导,但最终我发现字典推导也很有用,特别是在交换字典的键和值的时候。

代码语言:javascript
复制
my_phrase = ["No", "one", "expects", "the", "Spanish", "Inquisition"]
my_dict = {key: value for value, key in enumerate(my_phrase)}
print(my_dict)
reversed_dict = {value: key for key, value in my_dict.items()}
print(reversed_dict)

输出:
{"Inquisition": 5, "No": 0, "expects": 2, "one": 1, "Spanish": 4, "the": 3}
{0: "No", 1: "one", 2: "expects", 3: "the", 4: "Spanish", 5: "Inquisition"}

用subprocess执行shell命令

代码语言:javascript
复制
import subprocess
output = subprocess.check_output("dir", shell=True)
print(output)

注意,用os库完成这个特定命令比用subprocess更好。我只想有一个大家都熟悉的命令。同时,一般来说,在subprocess中使用shell=True参数是非常糟糕的主意,在这里使用这个参数仅仅是为了能在一个IPython notebook单元中放置命令的输出。不要自己使用这个参数!下面是用os模块执行shell命令

代码语言:javascript
复制
import os
os.system("dir")

注意,这里的dir命令会立刻在shell中输出,不能够保存到文件(变量)中,如果想要保存到变量中,可以使用popen:

代码语言:javascript
复制
import os
output = os.popen("dir")
print output.read()

字典的.get()和.iteritems()方法

字典的get()方法可以设置默认值,当用get()查找的键不存在时,返回方法中的默认值参数是很有用的。与列表中的enumerate()相同,可以用键值元组迭代字典中的元素。

代码语言:javascript
复制
my_dict = {‘name’: ‘Lancelot’, ‘quest’: ‘Holy Grail’, ‘favourite_color’: ‘blue’}

print(my_dict.get("airspeed velocity of an unladen swallow", "African or European?n"))

for key, value in my_dict.iteritems():
    print(key, value, sep=": ")

输出:

代码语言:javascript
复制
African or European?

quest: Holy Grail
name: Lancelot
favourite_color: blue

如果要用for迭代输出字典,就要用到字典的iteritems()方法,这个方法在python3.x中已经废除了,取代的是items()方法,items()方法在python2.x中也存在

用于交换元素的元组解包

在VB中,每当需要交换两个变量时,都要用要一个愚蠢的临时变量:c = a; a = b; b = c

代码语言:javascript
复制
a = "Spam"
b = "Eggs"

print(a, b)

a, b = b, a
print(a, b)

输出:
Spam Eggs
Eggs Spam

内省工具Introspection tools

我知道dir()方法,我本以为help()方法和IPython中的?魔法命令是一样的,但help()的功能更强大。

代码语言:javascript
复制
my_dict = {"That": "an ex-parrot!"}

help(my_dict)

输出:

代码语言:javascript
复制
Help on dict object:

class dict(object)
 | dict() -> new empty dictionary
 | dict(mapping) -> new dictionary initialized from a mapping object"s
 | (key, value) pairs
 | dict(iterable) -> new dictionary initialized as if via:
 | d = {}
 | for k, v in iterable:
 | d[k] = v
 | dict(**kwargs) -> new dictionary initialized with the name=value pairs
 | in the keyword argument list. For example: dict(one=1, two=2)
 |
 | Methods defined here:
 |
 | __cmp__(...)
 | x.__cmp__(y) <==> cmp(x,y)
 |
 | __contains__(...)
 | D.__contains__(k) -> True if D has a key k, else False
 |
 | __delitem__(...)
 | x.__delitem__(y) <==> del x[y]
 |
 | __eq__(...)
 | x.__eq__(y) <==> x==y
 |

[TRUNCATED FOR SPACE]

 | 
 | update(...)
 | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
 | If E present and has a .keys() method, does: for k in E: D[k] = E[k]
 | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
 | In either case, this is followed by: for k in F: D[k] = F[k]
 |
 | values(...)
 | D.values() -> list of D"s values
 |
 | viewitems(...)
 | D.viewitems() -> a set-like object providing a view on D"s items
 |
 | viewkeys(...)
 | D.viewkeys() -> a set-like object providing a view on D"s keys
 |
 | viewvalues(...)
 | D.viewvalues() -> an object providing a view on D"s values
 |
 | ----------------------------------------------------------------------
 | Data and other attributes defined here:
 |
 | __hash__ = None
 |
 | __new__ =
 | T.__new__(S, ...) -> a new object with type S, a subtype of T
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-05-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器学习算法与Python学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • enumerate(list)
  • 链式比较操作符
  • collections.Counter
  • 字典推导
  • 用subprocess执行shell命令
  • 字典的.get()和.iteritems()方法
  • 用于交换元素的元组解包
  • 内省工具Introspection tools
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档