slice

Remove an element of a slice in a struct [duplicate]

时间秒杀一切 提交于 2019-12-02 17:04:25
问题 This question already has answers here : How to change struct variable content? (1 answer) Why can't I append to a slice that's the property of a struct in golang? (1 answer) Closed 2 years ago . I have a struct "Guest" which contains metadata of a party guest (a unique ID, name, surname and a list of the unique IDs of the guests who are friends of this guest. type Guest struct { id int name string surname string friends []int } I have the following code to remove an ID from the list of

Go: Append if unique

让人想犯罪 __ 提交于 2019-12-02 16:31:16
Is there a way to check slices/maps for the presence of a value? I would like to add a value to a slice only if it does not exist in the slice. This works, but it seems verbose. Is there a beter way to do this? orgSlice := []int{1, 2, 3} newSlice := []int{} newInt := 2 newSlice = append(newSlice, newInt) for _, v := range orgSlice { if v != newInt { newSlice = append(newSlice, v) } } newSlice == [2 1 3] Your approach would take linear time for each insertion. A better way would be to use a map[int]struct{} . Alternatively, you could also use a map[int]bool or something similar, but the empty

Why does Python allow out-of-range slice indexes for sequences?

淺唱寂寞╮ 提交于 2019-12-02 16:04:14
So I just came across what seems to me like a strange Python feature and wanted some clarification about it. The following array manipulation somewhat makes sense: p = [1,2,3] p[3:] = [4] p = [1,2,3,4] I imagine it is actually just appending this value to the end, correct? Why can I do this, however? p[20:22] = [5,6] p = [1,2,3,4,5,6] And even more so this: p[20:100] = [7,8] p = [1,2,3,4,5,6,7,8] This just seems like wrong logic. It seems like this should throw an error! Any explanation? -Is it just a weird thing Python does? -Is there a purpose to it? -Or am I thinking about this the wrong

Contains method for a slice

故事扮演 提交于 2019-12-02 15:47:44
Is there anything similar to a slice.contains(object) method in Go without having to do a search through each element in a slice? Mostafa has already pointed out that such a method is trivial to write, and mkb gave you a hint to use the binary search from the sort package. But if you are going to do a lot of such contains checks, you might also consider using a map instead. It's trivial to check if a specific map key exists by using the value, ok := yourmap[key] idiom. Since you aren't interested in the value, you might also create a map[string]struct{} for example. Using an empty struct{}

Why are slices in Python 3 still copies and not views?

梦想与她 提交于 2019-12-02 15:24:28
As I only now noticed after commenting on this answer , slices in Python 3 return shallow copies of whatever they're slicing rather than views. Why is this still the case? Even leaving aside numpy's usage of views rather than copies for slicing, the fact that dict.keys , dict.values , and dict.items all return views in Python 3, and that there are many other aspects of Python 3 geared towards greater use of iterators, makes it seem that there would have been a movement towards slices becoming similar. itertools does have an islice function that makes iterative slices, but that's more limited

how to get the last part of a string before a certain character?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 15:23:05
I am trying to print the last part of a string before a certain character. I'm not quite sure whether to use the string .split() method or string slicing or maybe something else. Here is some code that doesn't work but I think shows the logic: x = 'http://test.com/lalala-134' print x['-':0] # beginning at the end of the string, return everything before '-' Note that the number at the end will vary in size so I can't set an exact count from the end of the string. You are looking for str.rsplit() , with a limit: print x.rsplit('-', 1)[0] .rsplit() searches for the splitting string from the end

Is there any convenient way to get JSON element without type assertion?

纵饮孤独 提交于 2019-12-02 15:05:45
There is some inconvenience while processing JSON response from a web server. For example, I don't know the data structure (and don't want to model it) of the JSON in advance, and just want to get the value from it! So, for Python, I can just write value = response["body"][4]["data"]["uid"] //response is a dictionary But for Golang, I need to do the assertion for every element! value := response["body"].([]interface{})[4].(map[string]interface{})["data"].(map[string]interface{})["uid"] //response is a map[string]interface{} This is what I write in golang to get the value I need. Do you have

Why is this list slice treating 0 and 1 as the same in Python? [duplicate]

落爺英雄遲暮 提交于 2019-12-02 14:55:33
This question already has an answer here: Understanding slice notation 32 answers I'm a bit confused about slicing a list and the numbering here. Python tends to start from 0 instead of 1, and it's shown below to work in that way well enough. But if we're starting from 0, and going until 3, why am I not getting exam instead of exa ? After all, 0 - 3 is 4 numbers. >>> test = "example string" >>> print test[:3] exa >>> print test[0:3] exa >>> print test[1:3] xa This is an intentional way, last element is exclusive. Why is it so? Firstly, my understanding it is because test[0:len(test)] should

Why can't I duplicate a slice with `copy()`?

烂漫一生 提交于 2019-12-02 14:13:25
I need to make a copy of a slice in Go and reading the docs there is a copy function at my disposal. The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst). But when I do: arr := []int{1, 2, 3} tmp := []int{} copy(tmp, arr) fmt.Println(tmp) fmt.Println(arr) My tmp is empty as it was before (I even tried to use arr, tmp ): [] [1 2 3] You can check it

Using assert_eq or printing large fixed sized arrays doesn't work

感情迁移 提交于 2019-12-02 13:59:41
问题 I have written some tests where I need to assert that two arrays are equal. Some arrays are [u8; 48] while others are [u8; 188] : #[test] fn mul() { let mut t1: [u8; 48] = [0; 48]; let t2: [u8; 48] = [0; 48]; // some computation goes here. assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1); } I get multiple errors here: error[E0369]: binary operation `==` cannot be applied to type `[u8; 48]` --> src/main.rs:8:5 | 8 | assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1); | ^^^^