📜  关于Python的10个有趣事实

📅  最后修改于: 2020-05-04 01:48:40             🧑  作者: Mango

由于Python的代码可读性和简单性,它是当今最受欢迎的编程语言之一。感谢其创建者Guido Van Rossum。
我用Python语言整理了10个有趣的事实的清单。他们来了:
1.实际上有一本书是蒂姆·彼得斯(Tim Peters)写的,名为《Python的禅》(The ZEN OF PYTHON),只需在解释器中输入import即可阅读。

# 在实际运行结果之前尝试猜测结果
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.
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!

2.一个人可以在Python中返回多个值。不相信吗?请参阅以下代码段:

# Python中的多个返回值!
def func():
   return 1, 2, 3, 4, 5
one, two, three, four, five = func()
print(one, two, three, four, five)

输出:

(1, 2, 3, 4, 5)

3.在Python中,可以将“ else”子句与“ for”循环一起使用。这是一种特殊的语法类型,仅当for循环自然退出且没有任何break语句时才执行。

def func(array):
     for num in array:
        if num%2==0:
            print(num)
            break # 情况1:调用了break,因此不会执行'else'。
     else: # 情况2:由于未调用break而执行了“ else"
        print("没有运行break。else执行")
print("第一种情况:")
a = [2]
func(a)
print("第二种情况:")
a = [1]
func(a)

输出:

第一种情况:
2
第二种情况:
没有运行break。else执行

4.在Python中,所有操作均通过引用完成。它不支持指针。

5.函数参数解压缩是Python的另一个很棒的功能。可以分别使用*和**将列表或字典解压缩为函数参数。这通常称为Splat运算符。这里的例子

def point(x, y):
    print(x,y)
foo_list = (3, 4)
bar_dict = {'y': 3, 'x': 2}
point(*foo_list) # 开箱list
point(**bar_dict) # 开箱字典

输出:

3 4
2 3

6.想在for循环中找到索引吗?用“enumerate”包装一个迭代器,它将产生该项及其索引。请参阅此代码段:

# 更快地了解索引
vowels=['a','e','i','o','u']
for i, letter in enumerate(vowels):
    print (i, letter)

输出:

(0, 'a')
(1, 'e')
(2, 'i')
(3, 'o')
(4, 'u')

7.一个可以在Python中链接比较运算符的答案= 1

# 链接比较运算符
i = 5;
ans = 1 < i < 10
print(ans)
ans = 10 > i <= 9
print(ans)
ans = 5 == i
print(ans)

输出:

True
True
True

8.我们不能定义Infinities吗?可是等等!不适用于Python。看到这个惊人的例子

# 正无穷大
p_infinity = float('Inf')
if 99999999999999 > p_infinity:
    print("该数字大于无穷大!")
else:
    print("无穷大是最大的")
# 消极无限
n_infinity = float('-Inf')
if -99999999999999 < n_infinity:
    print("该数字小于负无穷大!")
else:
    print("负无穷最小")

输出:

无穷大是最大的
负无穷最小

输出:

[0、1、2、3、4、5、6、7、8、9]
[0、1、2、3、4、5、6、7、8、9]

10.最后,Python的特殊Slice运算符。这是一种从列表中获取项目并进行更改的方法。请参阅此代码段

# 切片运算符
a = [1,2,3,4,5]
print(a[0:2]) # 选择元素[0-2),上限(不包括在内)
print(a[0:-1]) # 选择除最后一个以外的所有内容
print(a[::-1]) # 反转list
print(a[::2]) # 跳过2
print(a[::-2]) # 从后面跳过-2

输出:

[1,2]
[1、2、3、4]
[5,4,3,2,1]
[1、3、5]
[5、3、1]