# 第 30 期：Golang 并不简单

> @Author : Lewis Tian (<taseikyo@gmail.com>)
>
> @Link : github.com/taseikyo
>
> @Range : 2021-05-23 - 2021-05-29

## Weekly #30

[readme](/arts/readme.md) | [previous](/arts/wu-yue-1/202105w3.md) | [next](/arts/liu-yue-1/202106w1.md)

本文总字数 3595 个，阅读时长约：7 分 0 秒，统计数据来自：[算筹字数统计](http://www.xiqei.com/tools?p=tj)。

![](/files/-M_pPeuNeAsg1KnbXLFY)

\**Photo by* [*Airam Dato-on*](https://unsplash.com/@airamdatoon) *on* [*Unsplash*](https://unsplash.com/photos/OnAB7tWXxpA)

### Table of Contents

* [algorithm](/arts/wu-yue-1/202105w4.md#algorithm-)
* [review](/arts/wu-yue-1/202105w4.md#review-)
  * 你不了解 Python 的 10 个事实
  * 10 个非常有用的内置标准 Python 库/函数
  * 你可能不了解的 25 个 Python 技巧
* [tip](/arts/wu-yue-1/202105w4.md#tip-)
  * Linux 将 git 升级至最新版
  * Python 如何删除列表一个元素
* [share](/arts/wu-yue-1/202105w4.md#share-)
  * Golang 并不简单

### algorithm [🔝](/arts/wu-yue-1/202105w4.md#weekly-30)

### review [🔝](/arts/wu-yue-1/202105w4.md#weekly-30)

#### 1. [你不了解 Python 的 10 个事实](https://medium.com/pythoneers/10-facts-you-didnt-know-about-python-b18d87529c23)

1、*Python* 这个名字并不是来自 python（蟒蛇），而是一个电视节目（*Monty Python's Flying Circus*），而 Guido van Rossum 是该节目的忠实观众，于是取名 Python

2、Python（1991）比 Java（1995）更早出现

3、Python 是一个业余爱好项目（*Hobby Project*）

4、Python 有许多变体

* CPython，用 C 和 Python 编写的，将 Python 代码编译成字节码，同时使用编译器和解释器
* JPython，在 Java 平台上运行 Python 代码
* Brython，在浏览器上运行，类似于 JavaScript
* MicroPython，适用于微控制器

5、运行慢但仍然是最常用的语言之一

6、一切皆引用（reference）

7、在火星上运行（*Running On Mars*），这一点是什么鬼哦

You will get surprised to know that python is running on mars. Texting robots on Mars using python to send images to the earth. It uses `request` module to communicate with the API on mars.

8、可以定义无限的值

```python
number = float('Inf')
```

9、2015 年，Python 取代法语成为小学最流行的语言，数据显示，70% 的家长更喜欢孩子学 Python 而不是法语（法国人民这么疯狂的吗？）

10、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.
# 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. [10 个非常有用的内置标准 Python 库/函数](https://towardsdatascience.com/10-surprisingly-useful-base-python-functions-822d86972a23)

1、lambda

```python
mean = lambda x : sum(x) / len(x)

x = [5, 10, 15, 20]
print(mean(x))
```

2、shutil

`shutil` 库是文件系统上的一个高级接口，基于 `os` 库实现。

```python
import shutil

shutil.copyfile('mydatabase.db', 'archive.db')
# 移动文件/文件夹
shutil.move('/src/High.py', '/packages/High')
# 删除文件夹
shutil.rmtree('/src')
```

记得用它可以直接删除文件夹，而 `os` 就不太行。

3、glob

glob 库用于搜索目录中的通配符

```python
import glob

glob.glob('*.ipynb')
```

4、argparse

命令行解析库，我之前用过

```python
import argparse

parser = argparse.ArgumentParser(prog='top',
                                 description='Show top lines from the file')
parser.add_argument('-l', '--lines', type=int, default=10)

args = parser.parse_args()
```

5、re

这个无需多说，正则匹配是很强大一个库

6、math

说实话，这个库我用的很少很少

尽管里面有很多关于数学计算的函数，但是我用到的时候很少

```python
import math

math.log(1024, 2)
```

7、statistics

虽然是个内置标准库，但这个库没听过，更别说用过 2333

```python
import statistics as st

st.mean(data)
st.median(data)
st.variance(data)
```

8、urllib

一般都是用 `requests` 库去了，基本没咋用这个库

9、datetime

计算时间经常用到，但是总和 `time` 纠缠不清，每次都要去查

```python
import datetime as dt

now = dt.date.today()
print(now.year)
print(now.month)
```

10、zlib

用来压缩的一个库，没用过，我之前是直接用 `os.system` 调 7z 来进行压缩的

其中最重要的是压缩和解压函数：`compress` 和 `decompress`

总的来说还是习惯用啥库就用啥库，管他是内置标准库还是第三方库，库写出来不就是给人用的吗，好用顺手就行。

#### 3. [你可能不了解的 25 个 Python 技巧](https://betterprogramming.pub/25-python-tips-and-tricks-you-are-probably-not-aware-of-cc122b079e18)

1、any & all

最后一个有丶意思，至少一真一假

```python
x = [True, True, False]

if any(x):
    print("At least one True")

if all(x):
    print("None False")

if any(x) and not all(x):
    print("At least one True and one False")
```

2、bashplotlib

可以在控制台画图，一个三方库

3、Collections

我知道这个库里面有很多好用的模块，比如我用过的有 namedtuple 和 defaultdict

```python
from collections import OrderedDict, Counter

# memorize the order of adding keys
x = OrderedDict(a=1, b=2, c=3)

# count the frequency of each character
y = Counter("Hello World!")
```

4、dir

这个在前面的某一篇文章中介绍过，用来查看 Python对象的内部属性

5、emoji

用来展示 emoji 的三方库

```python
from emoji import emojize

print(emojize(": thumbs_up:"))
```

6、`__future__`

这个库里面也有很多好用的模块

7、geopy

从一系列不同的地理编码服务中提取 api 来获得该地点的完整地址、其纬度、经度，甚至其海拔高度

```python
from geopy import GoogleV3

place = "37 Tavistock Pl, Saint Pancras, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)
```

8、howdoi

有意思的命令行工具，使用 pip 安装

```bash
$ howdoi vertical alignn css
$ howdoi for loop in java
$ howdoi undo commits in git
```

9、inspect

inspect 库在理解代码正在做什么方面也很有用

```python
import inspect

print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)
```

10、[jedi](https://jedi.readthedocs.io/en/latest/docs/usage.html)

这是一个自动补全和代码分析的库，查了一下有 Sublime 的插件

11、`**kwargs`

字典中的键是参数的名称，值是传递给函数的值

```python
dictionary = {"a": 1, "b": 2}

def someFunction(a, b):
    print(a + b)
    return

# 2 applications of the function aFunction identical:
someFunction(**dictionary)
someFunction(a=1, b=2)
```

12、列表推导

老生常谈了

13、map

14、[newspaper3k](https://github.com/codelucas/newspaper)

它允许你从一系列领先的国际出版物中检索新闻文章和相关的元数据。

你可以恢复图像、文本和作者名称。

它甚至还有内置的 NLP 功能。

如果你正在考虑在下一个项目中使用 BeautifulSoup 或者其他网络抓取库，那么为自己节省时间和精力，并安装 newspaper3k。

*听上去很牛逼的样子*

15、操作符重载

```python
class Thing:
    def __init__(self, value):
        self.__value = value

    def __gt__(self, other):
        return self.__value > other.__value

    def __lt__(self, other):
        return self.__value < other.__value


something = Thing(100)
nothing = Thing(0)
# True
something > nothing
# False
something < nothing
# Error
something + nothing
```

16、pprint

用过，格式化打印，比默认的 print 输出更好看

17、Tail

Python 支持多线程，标准库中的 Queue 模块为此提供了便利

此模块允许实现排队数据结构，这些数据结构允许根据特定的规则添加和检索条目（FIFO、LIFO）

18、`__repr__`

```python
class someClass:
    def __repr__(self):
        return "<some description here>"


someInstance = someClass()
# display <some description here>
print(someInstance)
```

19、sh

它允许您像调用普通函数一样调用任何程序，这对于自动化工作流和任务非常有用，所有这些都来自 Python 内部。

```python
import sh

sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')
```

20、类型注解

Python 3.5+

```python
from typing import List

Vector = List[float]
Matrix = List[Vector]

def addMatrix(a: Matrix, b: Matrix) -> Matrix:
    result = []
    for i, row in enumerate(a):
        result_row = []
        for j, col in enumerate(row):
            result_row + = [a[i][j] + b[i][j]]
        result + = [result_row]
    return result


x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]
z = addMatrix(x, y)
```

21、uuid

```python
import uuid

user_id = uuid.uuid4()
print(user_id)
```

22、虚拟环境

```python
python -m venv my-project
source my-project/bin/activate
pip install all-the-modules
```

23、wikipedia

```python
import wikipedia

result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
    print(link)
```

24、xkcd

幽默是 Python 语言的一个关键特征ーー毕竟，它的名字来源于英国喜剧系列片《巨蟒剧团的飞翔的马戏团》。许多 Python 官方文档都引用了该系列中最著名的小品。

然而，幽默感并不仅限于文件，试试下面这句话：`import antigravity`

25、zip

用两个列表来构建一个字典

```python
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
```

zip 函数接受许多迭代对象并返回元组列表，每个元组根据输入对象的位置索引对其元素进行分组。

可以通过调用 `*zip()` 来 "解压缩" 对象

真受不了这个作者的代码风格，乱加空格，括号加空格（`( self )`），点也加空格（`users = requests. get ( url ) . json ()`），服了。

### tip [🔝](/arts/wu-yue-1/202105w4.md#weekly-30)

#### 1. Linux 将 git 升级至最新版

```bash
polaris:arts (w30*) $ git --version
git version 2.25.1
polaris:arts (w30*) $ git.exe --version
git version 2.31.1.windows.1
```

这一看就不是最新的嘛，于是打算直接升级

但是直接 `sai git`，会说已经安装，而不是升级，于是搜了下

* <https://blog.csdn.net/qq_43247439/article/details/107941144>

1、添加 Git 官方的软件源

```bash
sudo add-apt-repository ppa:git-core/ppa
```

2、更新软件列表

```bash
sudo apt update
sudo apt upgrade
```

再检查：

```bash
polaris:arts (w30*) $ git --version
git version 2.31.1
```

#### 2. [Python 如何删除列表一个元素](https://www.php.cn/python-tutorials-423479.html)

1、remove

用 `remove(val)` 方法删除指定元素，没有该元素时报错

```python
number = [1, 3, 2, 0]
# 删除指定元素1，这里是int类型因此不需要引号
number.remove(1)
print(number)
# [3, 2, 0]
```

2、del

利用 `del[idx]` 函数删除指定索引数的元素

```python
number = [1, 3, 2, 0]
# 删除指定索引数的元素，这里 0 的索引数是 3
del number[3]
print(number)
# [3, 2, 0]
```

3、pop

利用 `pop(idx=-1)` 方法弹出元素，默认弹出最后一个元素

```python
number = [1, 3, 2, 0]
# 弹出索引数为 1 的元素
number.pop(1)
# 3
print(number)
# [1, 2, 0]
```

4、clear

`clear()` 会将列表中的元素清空

```python
number = [1, 3, 2, 0]
number.clear()
number
# []
```

### share [🔝](/arts/wu-yue-1/202105w4.md#weekly-30)

#### 1. [Golang 并不简单](https://www.arp242.net/go-easy.html)

大多人说 Go 简单，包括之前实验室的一个同学也说过

可能是说它语法简单，会 C 的人学 Go 还是挺快的，但是用起来并不简单

很简单一个例子：删除切片的某个值/索引

像上面的删除 Python 的列表的一个值有很多方法，但是删除 Go 切片中的一个值却没有对应的内置方法，只能手动实现：

```go
// 删除索引 i
list = append(list[:i], list[i+1:]...)

// 删除值 v
n := 0
for _, l := range list {
    if l != v {
        list[n] = l
        n++
    }
}
list = list[:n]
```

显然，这比 Python 麻烦多了，而据作者所说，Ruby 中也有对应的函数：`list.delete_at(i)` 和 `list.delete(value)`，显然这俩都比 Go 简单。

这段时间在学 Go，从哔哩哔哩上看了一个视频教程（[地址](https://www.bilibili.com/video/av540943769) | [笔记](https://github.com/taseikyo/go-algorithms/tree/master/learning/tutorial/wupeiqi-go-tutotial)），作者骚话一堆，不过看得出来确实是个技术佬

貌似还没更完？毕竟标题是 **69 天，从小白到高高手**

结果只更新到第八天，不知道后面啥时候才能更完（；；）

[readme](/arts/readme.md) | [previous](/arts/wu-yue-1/202105w3.md) | [next](/arts/liu-yue-1/202106w1.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://taseikyo.gitbook.io/arts/wu-yue-1/202105w4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
