Python 的魅力在哪里?


在本文中,我们将了解 Python 的哪些特性使其与众不同,并使其在其他语言中脱颖而出。

>>>import this

输出

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
The flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

一行代码交换两个变量

我们可以使用单一语句同时为多个变量赋值,如下所示

示例

 实时演示

a = 201
b = 786
print("Before swapping value of a ="+str(a)+" and b = "+str(b))
#Before swapping value
a, b = b, a
print("After swapping value of a ="+str(a)+" and b = "+str(b))
#After swapping value

输出

Before swapping value of a =201 and b = 786
After swapping value of a =786 and b = 201

枚举类型

枚举类型用于遍历列表和类似类型,而无需实际了解它们的长度。

示例

 实时演示

mylist = ['t','u','t','o','r','i','a','l']
for i, value in enumerate(mylist):
   print( i, ': ', value)

输出

0 : t
1 : u
2 : t
3 : o
4 : r
5 : i
6 : a
7 : l

Zip 方法

使用 zip 方法,我们可以同时遍历多个列表,如下面的代码所示。

示例

 实时演示

mylist1 = ['t','u','t','o','r','i','a','l']
mylist2 = ['p','o','i','n','t']
for i,j in zip(mylist1,mylist2):
   print( i, ':', j)

输出

t : p
u : o
t : i
o : n
r : t

反转列表

使用内置的 reversed 方法(),我们可以直接获得反转后的列表,而无需任何循环结构。

示例

 实时演示

list_inp = ['t','u','t','o','r','i','a','l']
print(list(reversed(list_inp)))

输出

['l', 'a', 'i', 'r', 'o', 't', 'u', 't']

使用交互式 "_" 运算符。

此运算符用于命令行上打印或显示先前执行的操作的输出。

>>> 12 + 12
24
>>> _
24
>>> print(_)
24

我们都知道,在 Python 中不需要数据类型声明,我们可以在程序中多次更改变量的数据类型。

结论

在本文中,我们学习了 Python 中有哪些特性使其变得酷炫,并对程序员更具吸引力。

更新于: 2019年8月29日

187 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告