@Python 程序员,如何最大化提升编码效率?
作者 | Enoch CK
译者 | 刘畅
整理 | Jane
出品 | Python大本营
【导语】无论你是一位高级的AI工程师还是学生,你都会在工作或学习过程中需要用到 Python。自 1991 年首次发布后,Python 很快就成为了程序员和技术人员最喜欢的语言。作为一种拥有相对简单语法的高级解释语言,Python 成为了大家的不二之选。 一些集成的 Python 库也被应用在各个领域,如生物信息学(biopython),数据科学(pandas),机器学习(keras / tensorflow)甚至天文学(astropy)。尽管 Python 的执行速度比Java或其他语言慢得多,但无可否认它提高了工作效率。
(图片来源:原文引用自 Stack Overflow)
在这篇文章中,作者总结了在 Python 编程过程 5 个有助于提高编码效率的编程技巧。希望大家在改进代码时,这篇文章能提供一丝灵感。
技巧一:使用单行(one-liners)简化语句
每次看到那么多行的条件语句的时候,是不是都觉得头好痛? 如果简单一些的还好说,能找出不同条件下的关系,但是复杂的简直就是要迷失自我了。今天给大家介绍的 Python 单行功能也许能帮你解决这个困扰。例如,条件语句:
1
2
3
4
5
6
>>>
if alpha >
7:
2
>>> beta =
9993
>>>
elif alpha ==
7:
4
>>> beta =
995
>>>
else:
6
>>> beta =
0可以简化为:
1
>>> beta =
999if alpha >
7else (beta ==
99if alpha ==
7else0)
是不是很神奇! 如果仔细检查我们写的代码,一定可以找到能简化的代码。除了条件语句之外,for 循环也可以简化。 例如,将整数列表加倍:
1
2
3
4
>>> lst = [
1,
3,
5]
2
>>> doubled = []
3
>>>
for num
in lst:
4
>>> doubled.append(num*
2)
可以简化为一行:
1
>>> doubled = [num *
2for num
in lst]
当然,如果将所有内容都链接成一行,可能会有点麻烦。同时,还要确保你的代码中没有过度使用单行代码。
技巧二:字符串快速操作
要反转字符串,我们只需添加 ::-1 作为列表索引,就可以让你的工作非常轻松。
1
2
3
>>> a =
"ilovepython"2
>>>
print a[::
-1]
3
nohtypevoli
同样的技巧也可以应用于整数列表。在 Python 中,字符串操作非常简单。 例如,如果要使用以下的预定义变量 str1、str2 和 lst3 来输出一个句子。
1
2
3
>>> str1 =
"Totally"2
>>> str2 =
"Awesome"3
>>> lst3 = [
"Omg",
"You",
"Are"]
只需使用.join()方法和算术运算符即可创建所需的句子。
1
2
3
4
>>>
print' '.join(lst3)
2
Omg You Are
3
>>>
print' '.join(lst3)+
' '+str1+
' '+str2
4
Omg You Are Totally Awesome
除了字符串操作,还建议大家了解更多有关正则表达式的方法,以便更有效地搜索字符串和过滤模式。
技巧三:嵌套的列表组合
itertools 是我最喜欢的 Python 库之一。试想一下,你的代码中有十几个列表,经过一些操作后,会得到一个深度嵌套的列表。 itertools 正是用来解决语法混乱的工具。
1
2
3
4
5" An investment in knowledge pays the best interest."
>>>
import itertools
2
>>> flatten =
lambda x: list(itertools.chain.from_iterable(x))
3
>>> s = [[
'"',
'An',
'investment'], [
'in'], [
'knowledge'], [
'pays'], [
'the',
'best'], [
'interest."',
'--'], [
'Benjamin'], [
'Franklin']]
4
>>> print(
' '.join(flatten(s)))
5" An investment in knowledge pays the best interest."
-- Benjamin Franklin
从上面的例子中可以看出,我们可以使用 .join()和 itertools 方法来组合嵌套的列表和字符串。itertools 中的 .combinations()方法可以用于从输入迭代中返回元素的长度子序列。
技巧四:简单的数据结构
回到技巧一,可以非常容易的使用单行程序来初始化Python中的数据结构。 Harold Cooper 使用以下代码实现了单行树结构:
1
>>>
deftree():return defaultdict(tree)
上面显示的代码只是定义了一个默认值为树的字典。
1
>>> reduce( (
lambda r,x: r-set(range(x**
2,N,x))
if (x
in r)
else r), range(
2,N), set(range(
2,N)))
Python 还拥有一个强大的库,如 Collections,它可以帮助您解决各种现实问题,不用编写冗长的代码。
1
2
3
4
>>>
from collections
import Counter
2
>>> myList = [
1,
1,
2,
3,
4,
5,
3,
2,
3,
4,
2,
1,
2,
3]
3
>>> print(Counter(myList))
4
Counter({
2:
4,
3:
4,
1:
3,
4:
2,
5:
1})
技巧五:轻松打印(print)
最后分享给大家的是,我希望自己能在学习初期的时候就知道的一个技巧。 我们不需要使用 .join()和循环,就可以打印一个带有字符串的数组。
1
2
31
>>> row = [
"1",
"bob",
"developer",
"python"]
2
>>> print(
','.join(str(x)
for x
in row))
31
,bob,developer,python
单行代码则如下:
1
21
>>> print(*row, sep=
',')
21
,bob,developer,python
另一个巧妙的打印技巧是使用枚举。 enumerate 是Python的内置函数,非常有用。 因此,不需要写如下一个四行代码:
1
2
3
4
5
60
71
82
>>> iterable = [
'a',
'b',
'c']
2
>>> c =
03
>>>
for item
in iterable:
4
>>>
print c, item
5
>>> c+=
160
a
71
b
82
c
只需两行就可以完成同样的工作:
1
2
>>>
for c, item
in enumerate(iterable):
2
>>>
print c, item
Python 中有成千上万的打印技巧,比如 pprint,以后还可以再与大家进行分享。
本次内容就先为大家介绍这五个技巧。 如果你还知道其他的Python技巧,也可以留言和大家一起分享。
原文链接:https://towardsdatascience.com/five-python-tricks-you-need-to-learn-today-9dbe03c790ab
热 文 推 荐
print_r(
'点个好看吧!');
var_dump(
'点个好看吧!');
NSLog(@
"点个好看吧!");
System.out.println(
"点个好看吧!");
console.log(
"点个好看吧!");
(
"点个好看吧!");
printf
(
"点个好看吧!\n");
cout <<
"点个好看吧!" << endl;
Console.WriteLine(
"点个好看吧!");
fmt.Println(
"点个好看吧!");
Response.Write(
"点个好看吧!");
alert("点个好看吧!")
echo "点个好看吧!"
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。