FAQ Database Discussion Community


Use a dope vector to access arbitrary axial slices of a multidimensional array?

c,multidimensional-array,slice,matrix-multiplication,transpose
I'm building a suite of functions to work with a multidimensional-array data structure and I want to be able to define arbitrary slices of the arrays so I can implement a generalized inner product of two arbitrary matrices (aka Tensors or n-d arrays). An APL paper I read (I honestly...

Putting a list into a list at each new line

python,list,slice,bioinformatics,nested-lists
I am trying to create a new list (within a list) for each set of kmers For example it should return: [['ATT', 'TTT', 'TTG', 'TGG', 'GGC'], ['TGC', 'GCC', 'CCT', 'CTT', 'TTA'], ['CGG', 'GGT', 'GTA', 'TAT', 'ATC'], ['GAA', 'AAA', 'AAA', 'AAT', 'ATT']] Instead of this: ['ATT', 'TTT', 'TTG', 'TGG', 'GGC', 'TGC',...

Why isn't .slice() working with Float32Array() but does with an Array()? [JavaScript]

javascript,arrays,slice
For some reason, I can't get .slice() to work with a Float32Array. If you replace Float32Array by Array, it works perfectly fine. The doc for Float32Array lists .slice() as a method, so I don't understand if there's a bug or something? Or is it 2:00 AM and I can't see...

How to slice (in Python) “all but the last n” items when n may be zero? [duplicate]

python,slice
This question already has an answer here: List slicing with dynamic index on [:index] 4 answers I have a list of items in Python and I need to get "all but the last N" items. It needs to work when N is zero (in which case I want the...

Slicing multidimensional numpy array to obtain a vector

python,arrays,numpy,slice
In this example I'm trying to create a vector by selecting relevant elements from a multidimensional array. #data n=3 rng = 4 x = np.array([0,1,2],dtype=int) y = np.array([0,3,1],dtype=int) P = np.reshape(np.arange(n*rng*rng),(n,rng,rng)) output = np.zeros(n) for i in range(n): output[i] = P[i,x[i],y[i]] This returns array([ 0., 23., 41.]) Now I'm trying...

Error when indexing with 2 dimensions in NumPy

python,numpy,slice
Why does this work: >>> (tf[:,[91,1063]])[[0,3,4],:] array([[ 0.04480133, 0.01079433], [ 0.11145042, 0. ], [ 0.01177578, 0.01418614]]) But this does not: >>> tf[[0,3,4],[91,1063]] IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,) What am I doing wrong?...

numpy take can't index using slice

python,arrays,numpy,slice
According to the numpy docs for take it does the same thing as “fancy” indexing (indexing arrays using arrays). However, it can be easier to use if you need elements along a given axis. However, unlike "fancy" or regular numpy indexing, using slices as indices appears to be not supported:...

Unmarshal XML to struct and convert to slice

xml,go,slice
I have a simple project in Golang which I use to learn this language. Main purpose of the "service" which I'm developing is to run a daemon to save URLs which are exposed as XML. This way I can "produce" my own read-later service. So far so good :). You...

String slicing issue

python,slice
Right now, I'm trying to understand how string slicing works. In the example: str='HELLO WORLD' If I try str[-2:1:-2], I get: LO L I thought I should get LO LE since we go backward until index 1. What is the problem with my reasoning? ...

Using every first element in a multidimensional array

python,arrays,list,multidimensional-array,slice
I had thought that if you ran perhaps print mdarray[::][1], you would print the first sub-element of every element in the array. Where did I go wrong with this? I especially need this for a p.plot(x,y[::][1]) where I definitely do not want to use a for loop, as it is...

Get slice of string with check mark character with javascript

javascript,string,slice
I need to check if a '✔' is at the end of one of my strings (a span) and it's not working, it works with other characters tho. so, i'm trying: console.log(document.getElementById('my_span').innerHTML.slice(-1)); and it shows empty space instead of ✔, but it works with other characters. How can i get...

Slicing a list from the end

python,list,slice
Say, I have a list of values: >>> a = [1, 2, 3, 4] How can I make it include the end value through slicing? I expected: >>> a[4:] [4] instead of: >>> a[4:] [] ...

Slicing and broadcasting multidimensional arrays in Julia : meshgrid example

multidimensional-array,slice,julia-lang
I recently started learning Julia by coding a simple implementation of Self Organizing Maps. I want the size and dimensions of the map to be specified by the user, which means I can't really use for loops to work on the map arrays because I don't know in advance how...

javascript split or slice?

javascript,split,slice
I have a function that grabs the current user on my page. The variable currentUser equals the full name of the user. Sometimes that is just FirstName LastName but other times it is FirstName MiddleName LastName. I want to be able to split(or slice) currentUser by " " and set...

Arithmetic in Python slicing, end behaviour

python,slice
I want to traverse a list in a certain arrangement of slices: l = range(10) for i in (0,1,2): print l[i:i + 3] # [0, 1, 2] # [1, 2, 3] # [2, 3, 4] however when I try to do it from the ending of the list, the case...

Python: Grab each word after certain character in string

python,string,split,slice,irc
I want to grab each word that has a + before it If I input the string: word anotherword +aspecialword lameword +heythisone +test hello I want it to return: aspecialword heythisone test ...

Why do Slices always have an even capacity?

swift,slice,capacity
I'm currently using the Slice type in a project. I noticed some weird behaviour, so I decided to take a closer look at Slices. While testing around I discovered this: var slice = Slice<Int>() var range = 1...9 let length = range.endIndex - range.startIndex println(" length of 'range': \(length)") //prints...

Python: read text file into array - unequal row distrubution

python,arrays,text,slice,data-processing
I need to process a large text file containing information on scientific publications, exported from the ScienceDirect search page. I want to store the data in an array of arrays, so that each paper is an array, and all papers are stored in a larger array. The good part is...

Adding element to slice in handlerfunc and return as a whole

go,slice
I'm writing a service to learn Go. My main function can be found below. It starts with reading an XML file and storing them in a slice. I have a /rss endpoint which outputs a RSS feed from the items stored in the "database". This is working fine. I also...

set column = some operation of other column values in a pandas dataframe structure

pandas,dataframes,slice
I'm trying to perform a simple operation of a pandas dataframe using the logic below. The values in the columns of interest are decimals (up to 1 decimal point). The value of the operation cannot be negative so in case it is I want 0 instead. I've tried 2 methods...

How to attribute to a slice of a pandas Dataframe pointed by a variable?

python,pandas,copy,dataframes,slice
The following commands show how to attribute to a slice: In [81]: a=pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]]) In [82]: a Out[82]: 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 In [83]: a.loc[1] = [10,11,12] In [84]: a Out[84]: 0 1 2 0 1 2 3 1 10...

What is the difference between Slice and Array

arrays,rust,slice,coercion
I am a newbie to Rust programming language. Why are both &[u8] and &[u8; 3] ok in this example? fn main() { let x: &[u8] = &[1u8, 2, 3]; println!("{:?}", x); let y: &[u8; 3] = &[1u8, 2, 3]; println!("{:?}", y); } EDIT: The fact that &[T; n] can coerce...

How to extract letters except from middle part by using slice operator in python?

python,list,python-2.7,slice
I was trying to understand below example with all possibilities. +---+---+---+---+---+---+---+---+---+ | C | O | M | P | U | T | E | R | S | +---+---+---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 7 8 9 -9 -8 -7 -6 -5 -4 -3 -2 -1...

A Smarter Way to Learning JavaScript: Chapter 23 - Strings: Finding Segments

javascript,slice,indexof
I am working through the chapters and exercises for A Smarter Way to Learning JavaScript, Chapter 23 covers Strings: Finding Segments using indexOf and lastIndexOf methods. In the example a second variable firstChar is assigned the value of a variable text which contains a string "World War II". The objective...

Does Python copy references to objects when slicing a list?

python,list,memory,copy,slice
When a list is sliced, are the references to its contents copied from the original list? I can imagine that this may not be necessary, but I read the opposite (mentioned in passing). This question matters for instance for the following idiom, in the case of a very long my_list:...

Slicing with sed

bash,shell,command,slice
I have a file named servers.txt which contains Mysqlserver=172.15.23.23 How can I slice out the IP after the '='? This didn't work: cat servers.txt | sed =* ...

Referencing a numpy arrray without creating an expensive copy

python,arrays,numpy,reference,slice
Let's say that I have a function that requires that NumPy ndarray with 2 axes, e.g., a data matrix of rows and columns. If a "column" is sliced from such an array, this function should also work, thus it should do some internal X[:, np.newaxis] for convenience. However, I don't...

How to keep a strong reference in Go?

arrays,go,slice
Is there any way I can keep a strong reference in Go? Given the following convoluted piece of code: package main import ( "fmt" ) func main() { slice := make([]int, 5) slice[3] = 25 // whatever index between 0 and 4 included I don't care slicesArray := make([]*[]int, 2)...

Using BLAS ?gemm on a subset of an array in fortran

arrays,fortran,slice,blas
The various LDx arguments to BLAS ?gemm functions are there to make it possible to operate on slices of larger arrays. For example, this small C program does a matrix multiplication of the top left and top right (100,100) submatrices of a (200,200) matrix, and stores the result in the...

Go: builtin make - does the capacity make a difference

go,slice
Consider wanting to dynamically fill an array/slice with exactly 5 elements. No more, and no less. (1) Slice with initial length 0 sl := []string{} for i := 0; i < 5; i++ { sl = append(sl, "abc") } (2) Slice with initial length set, no capacity sl := make([]string,...

Does go garbage collect parts of slices?

go,garbage-collection,slice
If I implement a queue like this... package main import( "fmt" ) func PopFront(q *[]string) string { r := (*q)[0] *q = (*q)[1:len(*q)] return r } func PushBack(q *[]string, a string) { *q = append(*q, a) } func main() { q := make([]string, 0) PushBack(&q, "A") fmt.Println(q) PushBack(&q, "B") fmt.Println(q)...

Array vs Slice: accessing speed

arrays,performance,go,benchmarking,slice
This question is about the speed of accessing elements of arrays and slices, not about the efficiency of passing them to functions as arguments. I would expect arrays to be faster than slices in most cases because a slice is a data structure describing a contiguous section of an array...

How to slice middle element from list

python,slice
Rather simple question. Say I have a list like: a = [3, 4, 54, 8, 96, 2] Can I use slicing to leave out an element around the middle of the list to produce something like this? a[some_slicing] [3, 4, 8, 96, 2] were the element 54 was left out....

Why does go allow slicing from len(slice)?

arrays,go,slice
Why does the following behavior occur: a := []int{1, 2, 3} fmt.Println(a[0:]) fmt.Println(a[1:]) fmt.Println(a[2:]) fmt.Println(a[3:])// doesn't panic - why?? fmt.Println(a[4:])// panics as expected Executable example...

When populating a slice with length set at runtime, do I absolutely need two loops, one for determining the length and one for populating?

arrays,loops,go,slice
So I have a function that removes punctuation from a string and puts those punctuation characters and their index into two slices: func removeAndIndexPunctuation(word string) (string, []rune, []int) { // Index punctuation numberOfPunct := 0 for _, char := range word { if unicode.IsPunct(char) { numberOfPunct += 1 } }...

In Go How to delete an item from slice of an Struct

go,slice
I have struct containing a slice of another struct. I have added methods for Addition and Deletion of an item from the slice but addition is working deletion is not. I am new to Go so I am not able to understand why slice reassignment does not gets reflected in...

Is there a way to write generic code to find out whether a slice contains specific element in go?

go,slice,contains
I want to know is there a generic way to write code to judge whether a slice contains a element, I find it will frequently useful since there is a lot of logic to fist judge whether specific elem is already in a slice and then decide what to do...

How can I cut off characters from a specific column in a table?

javascript,jquery,angularjs,substring,slice
There are quite a few similar issues on here, but none of those solutions seem to work. I have a table where the content is dynamically loaded in via some voodoo, and I want to take the first 4 characters from the first <td> of each row off. The row...

indexing/slicing in numpy array to modify it

python,numpy,indexing,slice
I have a numpy array A and I want to modify values in it using a indexing list B. But the thing is in my slicing I can have an element of the array multiple times... This example will explain better what I mean by that : import numpy as...

Slice can not convert to string

string,go,type-conversion,slice
func (this *AdminModel) Login(v_name string, v_pwd string) (bool, error, uint) { o := orm.NewOrm() v_pwd_encrypt_byte := md5.Sum([]byte(v_pwd)) v_pwd_encrypt := string(v_pwd_encrypt_byte[:]) t_admin := Admin{Name: v_name, Pwd: v_pwd_encrypt} fmt.Printf("username:%v password:%v\n", v_name, v_pwd_encrypt_byte) fmt.Printf("username:%v password:%v\n", v_name, v_pwd_encrypt_byte[:]) fmt.Printf("username:%v password:%v\n", v_name, v_pwd_encrypt) err := o.Read(&t_admin, "Name", "Pwd") if err != nil { return false,...

Slice and attribute in django template

django,django-templates,slice
I am tried to create a slice in django template and get an attribute. How can i do in django template something like this: python code: somelist[1].name please help...

Re-slicing and garbage collection

go,garbage-collection,slice
When re-slicing, do i need to set the elements that are not in the slice anymore to nil,does it have any effect on garbage collection? type X struct { Value string } func main() { Xs:=[]*X{&X{"a"},&X{"b"},&X{"c"},&X{"d"}} X0:= Xs[0] Xs[0] = nil //does this line has any effect on the garbage...

Replace a list slice with a packed tuple

python,list,tuples,slice
I have a list of points in the form of tuples: myList = [(1,1), (2,2), (3,3), (4,4), (5,5)] I want to replace a slice of variable length with a new tuple (6,6) so the result is something like: myList = [(1,1), (6,6), (5,5)] I tried assigning the tuple to the...

How to access elements from slice using index which is passed by reference in golang

go,pass-by-reference,slice
I passed a reference of a slice to a function and I am making changes in the slice inside the function. Also I am trying to access an element from the slice using index. It is throwing exception in golang. What is the best way to access an element from...

Slices in Go: why does it allow appending more than the capacity allows?

go,append,slice,capacity
The capacity parameter in making a slice in Go does not make much sense to me. For example, aSlice := make([]int, 2, 2) //a new slice with length and cap both set to 2 aSlice = append(aSlice, 1, 2, 3, 4, 5) //append integers 1 through 5 fmt.Println("aSlice is: ",...

sorting javascript array slice

javascript,sorting,slice
In trying to create a sortable table, I am sorting the underlying array of data: var g = [ [ 'First Name', 'Last Name', 'Id', 'Age'], [ 'Joe', 'Blogs', '1', 24], [ 'Fred', 'Frog', '2', 18], ]; I want to sort everything except the header. g = g.sort(mycomparison); is no...

I need an explanation on slice()

javascript,function,slice,palindrome
I was completing javascript exercises and got stuck on creating a function which checks if a string is a palindrome. For your reference, this was the given solution. I understand what slice() does as a method, and I followed the function here until the point where it checks to see...

Remove elements in slice

go,slice
I am complete newbie in golang, I am trying to remove elements in one slice based on the elements in another slice. e.g input slice : urlList := []string{"test", "abc", "def", "ghi"} elements to remove slice : remove := []string{"abc", "test"} expected output slice : urlList := []string{"def", "ghi"} This...

difference between slice declaration and initialization

go,initialization,slice
What is the difference between a and b? I know that reflect.DeepEqual considers them not equal and I know that a is nil. Are there built in functions that easily show the difference? var a []foo b := []foo{} ...

golang The zero value of a slice is not nil.

go,slice
I was following the example https://tour.golang.org/moretypes/10 I modified the code expecting to get the same result. I did not. Is this a bug, or a documentation error? The tour states A nil slice has a length and capacity of 0. My y variable has a length and capacity of 0....

Go-lang: How to convert slice to fixed size array?

arrays,go,slice
I want to convert a fixed size array from a slice: func gen(bricks []Brick) { if len(bricks) == 16 { if check(Sculpture{bricks}) { var b [16]Brick = bricks[0:16]; } } } But this results in: cannot use bricks[0:16] (type []Brick) as type [16]Brick in assignment How to convert a slice...

Slice index out of range but one space is free

go,slice
I am trying to figure out how slice resizing works and I have the following sample: package main import ( "fmt" ) func main() { s := []byte{'A', 'W', 'T', 'Q', 'X'} b := s[2:4] fmt.Println(s, len(s), cap(s)) fmt.Println(string(b), len(b), cap(b)) b[1] = 'H' b[2] = 'V' fmt.Println(string(b)) } The...

Different slicing behaviors on left/right hand side of assignment operator

python,python-3.x,operators,slice,deep-copy
As a Python newbie coming from the C++ background, the slicing operator in Python (3.4.x) looks ridiculous to me. I just don't get the design philosophy behind the "special rule". Let me explain why I say it's "special". On the one hand, according to the Stack Overflow answer here, the...

Slicing rows of pandas dataframe between

pandas,subset,slice
I have a pandas dataframe with a column that marks interesting points of data in another column (e.g. the locations of peaks and troughs). I often need to do some computation on the values between each marker. Is there a neat way to slice the dataframe using the markers as...

NumPy slice notation in a dictionary

python,python-2.7,numpy,slice
I wonder if it is possible to store numpy slice notation in a python dictionary. Something like: lookup = {0:[:540], 30:[540:1080], 60:[1080:]} It is possible to use native python slice syntax, e.g. slice(0,10,2), but I have not been able to store more complex slices. For example, something that is multidimensional...

Python 2D numpy.ndarray slicing without comma

python,numpy,slice
Recently someone told me to extract the first two columns of a 2D numpy.ndarray by firstTwoCols = some2dMatrix[:2] Where is this notation from and how does it work? I'm only familiar with the comma separated slicing like twoCols = some2dMatrix[:,:2] The : before the comma says to get all rows,...

Why use arrays instead of slices?

arrays,go,slice
I have been reading up on Go, and got stumped thinking about this fundamental question. In Go, it is quite clear that slices are more flexible, and can generally be used in place of arrays when you need a sequence of data. Reading most of the documentation, they seem to...

How to idiomatically copy a slice?

rust,slice
In Go, copying slices is standard-fare and looks like this: # It will figure out the details to match slice sizes dst = copy(dst[n:], src[:m]) In Rust, I couldn't find a similar method as replacement. Something I came up with looks like this: fn copy_slice(dst: &mut [u8], src: &[u8]) ->...

Slicing a Python OrderedDict

python-2.7,slice,ordereddictionary
In my code I frequently need to take a subset range of keys+values from a Python OrderedDict (from collections package). Slicing doesn't work (throws TypeError: unhashable type) and the alternative, iterating, is cumbersome: from collections import OrderedDict o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) # want to...

golang, trying to join a slice into a string

join,go,slice
package main import ( "fmt" "strings" ) func main() { reg := [...]string {"a","b","c"} fmt.Println(strings.Join(reg,",")) } gives me an error of: prog.go:10: cannot use reg (type [3]string) as type []string in argument to strings.Join Is there a more direct/better way than looping and adding to a var?...

How to populate struct slice using array?

arrays,struct,go,slice
In Go is it possible to populate a struct slice? My data is an array of strings. a := [string1, string2, string3, string4] type User struct { NickName string } var u []User How do I populate u with the contents of a?...

How to efficiently index into a 1D numpy array via slice ranges

python,arrays,numpy,slice
I have a big 1D array of data. I have a starts array of indexes into that data where important things happened. I want to get an array of ranges so that I get windows of length L, one for each starting point in starts. Bogus sample data: data =...

Parenthesis after a slice in go?

go,slice
I've recently started learning go, and following through a tutorial. In the tutorial there is the line: p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")} They have a slice with parenthesis defined: []byte("This is a sample Page.") However from all the docs I've read I've never seen parenthesis...

Script Slicing in Python

python,slice
I am new in programming and Python. I have a list in my hand and I want to manipulate my list as each words will be consisted of (first) 6 letters maximum. Sample list as below. new_list = ['partiye', 'oy', 'vermeyecegimi', 'bilerek', 'sandiga', 'gidecegim'] I used below code for cutting...

C++ matrix template class slice

c++,templates,c++11,matrix,slice
In order to learn about C++ templates I am writing a simple Matrix class. So far it has been working well, but I want to add the ability to slice the Matrix to extract a sub-matrix. I am struggling to figure out how to define the size of the return...

Why can not I copy a slice with copy in golang?

go,slice
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...

How to pass variable parameters to Sprintf in golang

go,slice
I'm lazy, want to pass many variables to Printf function, is it possible? (The sample code is simplified as 3 parameters, I require more than 10 parameters). I got the following message: cannot use v (type []string) as type []interface {} in argument to fmt.Printf s := []string{"a", "b", "c",...

Python - Iterating through list of list as a matrix (slice)

python,arrays,list,numpy,slice
I want to iterate through list of list. To iterate through every list inside list also. list=[[0.9 0.8 0.1 0.2 0.5 ][0.5 0.3 0.2 0.1 0.7 ][0.6 0.1 0.3 0.2 0.9][0.3 0.7 0.4 0.1 0.8]] Thus to iterate through every list inside, only to the third position, eg: list=[[0.9 0.8...

Conversion of a slice of string into a slice of custom type

go,type-conversion,slice
I'm quite new to Go, so this might be obvious. The compiler does not allow the following code: (http://play.golang.org/p/3sTLguUG3l) package main import "fmt" type Card string type Hand []Card func NewHand(cards []Card) Hand { hand := Hand(cards) return hand } func main() { value := []string{"a", "b", "c"} firstHand :=...

Remove slices from array in PHP

php,arrays,slice
I have a PHP array and I want to remove slices of elements with the following rule: when an element has visible=0, I want remove the element and the following elements after it, no matter if they are visible or not. In this example, I would like to remove two,...

Split an array into new arrays (each with a unique name) [duplicate]

ruby,arrays,iteration,slice
This question already has an answer here: How to dynamically create a local variable? 1 answer I'm trying to slice an array into equal sizes (rounded down) and save each section to respective variables. The method each_slice has worked to grab n-sized blocks. However I can't think of a...

Working with empty lists

python,for-loop,while-loop,slice
Okay so I am trying to create an empty list, then add integers to the list to then pick out the highest,lowest and 5 middle numbers( in descending order using a slice) and put them on display... seems simple enough.... def main(): nums = [] for i in range(20,80,9): nums.append(i)...

Extract characters from string after last period

python,regex,pandas,slice
I have an orderedDict: dict2.items(): [('A', <function __main__.percentile_50>), ('B', <function numpy.core.fromnumeric.sum>), ('C', <function numpy.core.fromnumeric.sum>), ('D', <function numpy.core.fromnumeric.mean>), etc... I want to create a column that says what descriptive was used (percentile_50, sum, mean, etc.) I'm thinking of finding the last . and then grabbing the characters after it up until...

Python Extracting a substring of variable length

python,regex,substring,extract,slice
I'm trying to extra the name of a module from some verilog code. For example: module uart (inputs, outputs, etc) I know I can use pythons slicing to get a substring, but that only uses indexes. I need to make it so that it slices kind of like this: string[6:...

Modified slice elements not accessible with map. What am I doing wrong?

dictionary,go,slice
I have a slice of a more or less complex struct and I want all elements of this slice to be accessible with a map. The map contains pointers to the slice elements. My problem is now that when I change the content of a slice element, it is not...

List slicing with dynamic index on [:index]

python,list,slice
I need to slice a list using negative dynamic indexes ([:-index]). This was easy until I realized that if the value of my dynamic index was 0, no items were returned, instead of returning the entire list. How can I implement this in a way that when the index is...

Split string in Python into chunks with constant length, but right-aligned

python,string,slice
Basically, I have a string like "12345678" and need a list containing this information, but split into substrings of length 3. The problem is, that I need it to be right-aligned, so the output must be ['12', '345', '678'] and NOT ['123', '456', '78']. How do I best achieve with...

Different performances in Go slices resize

go,stack,benchmarking,slice
I'm spending some time experimenting with Go's internals and I ended up writing my own implementation of a stack using slices. As correctly pointed out by a reddit user in this post and as outlined by another user in this SO answer Go already tries to optimise slices resize. Turns...

What does this notation do for lists in Python: “someList[:]”?

python,list,slice,notation,shallow-copy
I sometimes get across this way of printing or returning a list - someList[:]. I don't see why people use it, as it returns the full list. Why not simply write someList, whithout the [:] part?...

Getting size of an array passed in as an argument

arrays,rust,slice
I can't seem to make this work. I keep getting an error saying 'len' doesn't exist on type '&[str]'. fn testLength(arr: &[str]) { if arr.len >= 10 { // Do stuff } } I'm still pretty new to Rust, and I understand this is a pointer to a raw string...

multiply numpy ndarray with 1d array along a given axis

python,arrays,numpy,slice
It seems I am getting lost in something potentially silly. I have an n-dimensional numpy array, and I want to multiply it with a vector (1d array) along some dimension (which can change!). As an example, say I want to multiply a 2d array by a 1d array along axis...

Ruby on Rails Hash#slice method returns empty hash

ruby-on-rails-4,hash,slice,ruby-2.0,activesupport
Why does the first example return a hash with the two specified keys, while the second example returns an empty hash? User.last.slice(:created_at, :updated_at) => {"created_at"=>Fri, 22 May 2015 00:33:37 UTC +00:00, "updated_at"=>Fri, 22 May 2015 01:00:06 UTC +00:00} User.last.attributes.slice(:created_at, :updated_at) => {} Notice the the difference in the examples is...

Chop off text when it reaches certain word in Python

python,slice,toc,chop
I'm using Python and I have an HTML-code which I want to chop off as soon as it reaches the word "toc", but I can't figure out how to do, anyone having some nice ideas?

Concatenation of strings array issues in Python: Str(ArrayOfString[1])+“ ”+Str(ArrayOfString[2]) doesn't seem to work

string,python-2.7,concatenation,slice,string-length
Hi I have a problem with a python script, I don't manage to do a concatenation of 2 arrays of strings it returns- SyntaxError: can't assign to function call Here's my script: import os, sys, MySQLdb # connecting to a database db = MySQLdb.connect(host="localhost", user="MyUser", passwd="MyPassword",db="MyDB") cursor = db.cursor() cursor.execute("SELECT...

Python String: obtaining what's left after python string slice

python,string,slice
This substring related question appears to never mention another potential goal when slicing strings: obtaining what's left after a slice. Is there a way to get what's left over when performing a slice operation without two separate steps where you join what's left over? This would be brute force way,...

Python: Slicing string in three-character substrings

python,string,for-loop,slice
I am attempting to slice a string into triplets based on the characters like this: string1 = 'abcdef' substrings = 'abc', 'bcd', 'cde', 'def' I then want to compare these 'triplets to a second string and count their occurrence: string2 = 'abcijk' substrings of string1 in string2 = 1 ('abc')....

Python slice list at n and take the next x elements?

python,list,slice
I've not been able to Google this issue, I want to slice [1,2,3,4,5,6] at index 2 and take the next 3 elements (ie [3,4,5]). The notation list[start:stop:step] doesn't actually allow this or am I not aware of some Pythonic way?

How to get this data in a list?

python,list,csv,slice
I am new to Python and got the following data to work with: https://dl.dropboxusercontent.com/u/86876232/6358.csv The linked file is only a fraction of the entire data (the data should contain a bit over 15000 lists). First of all in what format is this data? And how do I get it from...