是什么使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方法,我们可以同时遍历多个列表,如下面的代码所示。
示例
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
倒转列表
通过使用内置的反向,method()
我们可以直接获取反向列表,而无需任何循环构造
示例
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中存在的所有功能,这些功能使其很酷,并且对程序员更具吸引力。