英文:
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]可能会复制范围内的所有元素,创建一个新的对象(对于内置的list和tuple来说是这样的)。
英文:
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 ofstringof 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 createa = [None]just to be able to index the list right away (in generala = [default_value] * size).b = make([]int, 1): same here, justb = []orb = [0]if you need to index the list right away. Note that Go initializes all elements to0for[]int.c = make(map[string]string): this creates a map withstringas 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 doc["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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论