如何在Python中模仿Golang的make()函数?

huangapple go评论92阅读模式
英文:

How to mimic Golang make() function in Python?

问题

我正在尝试将Go代码重写为Python,但我不理解Golang中的make()函数是如何工作的。

作为示例,我有以下代码,我正在尝试将其重写为Python:

a = [None] * 1
b = [0] * 1
c = {}

希望对你有所帮助。

英文:

I am trying to rewrite go code to python and I don't understand how the make() function in Golang works.

As an example I have this code which I'm trying to rewrite to Python:

a = make([]string, 1)
b = make([]int, 1)
c = make(map[string]string)

Any help is appreciated.

答案1

得分: 4

在Python中不需要使用make来创建任何东西...换句话说,不需要编写一个模拟make的函数。与Go不同,你不需要明确地分配某个对象,因为在Python中,对象的分配是隐式的,会在创建时自动进行。

  • a = make([]string, 1):这是一个大小为1、容量为1的string切片,在Python中,你可以直接创建一个空列表:a = [],然后使用.append()方法向其中添加字符串。与Go不同,Python的列表不要求所有元素都是相同类型的。如果你想要立即对列表进行索引,可以创建a = [None](通常是a = [default_value] * size)。
  • b = make([]int, 1):同样,在Python中只需b = []b = [0](如果需要立即对列表进行索引)即可。请注意,Go会将[]int的所有元素初始化为0
  • c = make(map[string]string):这将创建一个以string为键和值的映射。在Python中,最接近的东西是字典:c = {}。再次强调,Python中的类型不受限制,所以你可以随后执行c["foo"] = "bar"而没有问题。

请注意,Go的切片与Python的切片具有不同的语义。在Go中,执行a[1:10]会创建一个仅仅是底层对象的视图的切片,而在Python中,a[1:10]可能会复制范围内的所有元素,创建一个新的对象(对于内置的listtuple来说是这样的)。

英文:

No need to make anything in Python... or in other words, no need to write a function that mimics make. Unlike Go where you have to be explicit about allocating something, in Python this is implicit as objects are allocated automatically on creation for you.

  • a = make([]string, 1): this is a slice of string of size 1 and capacity 1, in Python you can just create an empty list instead: a = [] and then .append() strings into it. Unlike Go for slices or arrays, Python does not require all elements of a list to be of the same type. If you want you could create a = [None] just to be able to index the list right away (in general a = [default_value] * size).
  • b = make([]int, 1): same here, just b = [] or b = [0] if you need to index the list right away. Note that Go initializes all elements to 0 for []int.
  • c = make(map[string]string): this creates a map with string as keys and values. Closest thing in Python would be a dictionary: c = {}. And again, you are not constrained by types in Python so you can later do c["foo"] = "bar" without a problem.

NOTE THAT Go slices have different semantics than Python slices. Doing a[1:10] in Go creates a slice that is merely a view on the underlying object, while in Python a[1:10] potentially copies all the elements in the range creating a new object (this is true for the built-in list and tuple).

huangapple
  • 本文由 发表于 2022年2月6日 02:21:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/71000864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定