I have a array
arr=['a','b','c']
and a variable
var='a'
I am trying to remove the variable from array and append the resultant array to a new array.
newarray = []
if var in arr:
newarray.append(arr.remove(var))
print(newarray)
This does not print anything. However when I run only arr.remove(var) it works...I am not able to append the resultant smaller array to a new variable.
From your description, this is what you may be looking for:
arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
arr.remove(var)
newarray.append(arr)
print(newarray)
Output:
[['b', 'c']]
Note the output of following:
if var in arr:
print(arr.remove(var))
print(newarray.append(arr))
print(newarray)
Output:
None
None
[['b', 'c']]
arr.remove(var) and newarray.append(arr) work on list in place but do not return anything.
Hence newarray.append(arr.remove(var)) means newarray.append(None)
use pop() function instead. Change:
newarray.append(var)
print(arr.remove(var))
to:
newarray.append(arr.pop(0))
print(newarr)
Looks like your code got a bit mangled. Here's how to fix it:
arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
newarray.append(var)
arr.remove(var)
print(newarray)
To understand why your original code printed [None], you first need to understand array.remove(). array.remove is a void function: it does not return a value, only performs tasks. If you try to get or call its return value in a function such as array.append(), Python doesn't know how to react and returns None. The None value was then appended to the array properly by the array.append() function.
Related
I have a 2d array and I want to check whether an array exists inside the 2d array.
I have tried:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)
This should print true but it doesn't work.
Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.
You could use find + sameElements:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)
Consider using ArrayBuffer instead of Array, if you need mutable collection, like so
val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain)
which outputs
true
Also consider question What is the difference between ArrayBuffer and Array
A more elegant solution would be the following
val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)
Output
true
So in a swift playground file, I am trying to execute the following closure:
var list = [5, 4, 3]
var Arraymultiplier = {(list:Array) -> Array in
for value in list {
value*2
return list
}
}
Arraymultiplier(list)
When I do this though, I get an error saying that the generic type Array must be referenced in <..> brackets, but when I put the brackets, I get another error.
What's the right way to declare the array type as an input and a return?
Array is a generic type, meaning that it expects to see the actual type of the members of the array to be specified within < > immediately following Array:
var arrayMultiplier = {(list: Array<Int>) -> Array<Int> in
// do whatever you want here
}
Or, in the case of arrays, there is a convenient syntax that uses the [ ] characters and omits the need for Array reference at all:
var arrayMultiplier = {(list: [Int]) -> [Int] in
// do whatever you want here
}
I'm not sure what the original code sample was trying to do, but it looks like you might have been trying to build a new array with each item multiplied by 2. If so, then you might do something like:
let inputList = [5, 4, 3]
let arrayMultiplier = { (list: [Int]) -> [Int] in
var results = [Int]() // instantiate a new blank array of `Int`
for value in list { // iterate through array passed to us
results.append(value * 2) // multiply each `value` by `2` and add it to the `results`
}
return results // return results
}
let outputList = arrayMultiplier(inputList)
Or, obviously, you could efficiently achieve similar behavior using the map function:
let outputList = inputList.map { $0 * 2 }
I'm using Array(0, {i -> ""}) currently, and I would like to know if there's a better implementation such as Array()
plus, if I'm using arrayOfNulls<String>(0) as Array<String>, the compiler will alert me that this cast can never succeed. But it's the default implementation inside Array(0, {i -> ""}). Do I miss something?
As of late (June 2015) there is the Kotlin standard library function
public fun <T> arrayOf(vararg t: T): Array<T>
So to create an empty array of Strings you can write
val emptyStringArray = arrayOf<String>()
Just for reference, there is also emptyArray. For example,
var arr = emptyArray<String>()
See
doc
Array.kt
Empty or null? That's the question!
To create an array of nulls, simply use arrayOfNulls<Type>(length).
But to generate an EMPTY array of size length, use:
val arr = Array(length) { emptyObject }
Note that you must define an emptyObject properly per each data-type (beacause you don't want nulls). E. g. for Strings, emptyObject can be "". So:
val arr = Array(3) { "" } // is equivalent for: arrayOf("","","")
Here is a live example. Note that the program runs with two sample arguments, by default.
null array
var arrayString=Array<String?>(5){null}
var nullArray= arrayOfNulls<String>(5)
As mentioned above, you can use IntArray(size) or FloatArray(size).
I found two ways to create an empty array, the second way without a lambda:
var arr = Array (0, { i -> "" })
var arr2 = array<String>()
Regarding Kotlin's null strings, this is not allowed. You have to use String? type to allow strings to be null.
Use:
#JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
It returns an 0 size array of Strings, initialized with null values.
1. Wrong:
#JvmField val EMPTY_STRING_ARRAY = emptyArray<String>()
It returns arrayOfNulls<String>(0)
2. Wrong:
#JvmField val EMPTY_STRING_ARRAY = arrayOf<String>()
It returns an array containing the Strings.
Simplest way to initialise array and assigning values :
val myArray: Array<String> = Array(2) { "" }
myArray[0] = "Java"
myArray[1] = "Kotlin"
I want to get a range of objects from an array. Something like this:
var array = [1,3,9,6,3,4,7,4,9]
var newArray = array[1...3] //[3,9,6]
The above would access elements from index 1 to 3.
Also this:
newArray = array[1,5,3] // [3,4,6] would be cool
This would retrieve elements from index 1, 5 and 3 respectively.
That last example can be achieved using PermutationGenerator:
let array = [1,3,9,6,3,4,7,4,9]
let perms = PermutationGenerator(elements: array, indices: [1,5,3])
// perms is now a sequence of the values in array at indices 1, 5 and 3:
for x in perms {
// iterate over x = 3, 4 and 6
}
If you really need an array (just the sequence may be enough for your purposes) you can pass it into Array's init method that takes a sequence:
let newArray = Array(perms)
// newArray is now [3, 4, 6]
For your first example - with arrays, that will work as-is. But it looks from your comments like you're trying it with strings as well. Strings in Swift are not random-access (for reasons relating to unicode). So you can't use integers, they have an String-specific bidirectional index type:
let s = "Hello, I must be going"
if let i = find(s, "I") {
// prints "I must be going"
println(s[i..<s.endIndex])
}
This works :
var n = 4
var newArray = array[0..<n]
In any case in
Slicing Arrays in Swift you'll find a very nice sample of the Python slice using a extension to Arrays in Swift.
I cannot figure out how to add values to an empty array in Swift. I have tried started with empty array in two different ways:
var emptyArray : Int[]?
emptyArray = Int[]()
and
var emptyArray = []
(by the way, what is the difference with these two ways of creating empty arrays?)
I have tried to add an integer to the array with emptyArray.append(1), emptyArray += [1] but none works nor it is in the guide book (or maybe, it is hidden some where that I couldn't figure out). Both of these work if there is one or more values in it and this is driving me crazy! Please let me know how to if you know how to do it. Thank you!
First, create empty Int array:
var emptyArray : Int[] = []
or:
var emptyArray = Int[]()
Add number to that array (two ways):
emptyArray += [1]
emptyArray.append(2)
Array now contains [1, 2]
You need to first declare the empty array in Swift like this:
var emptyArray = [Int]()
You can then append that array with whatever value/variable you so choose like this:
emptyArray.append(6)
just be sure you keep in mind that trying to append a type that mismatches your array declaration will give you a compile error. For example, trying to append a string would error since this array was declared using the Int type.
Playgrounds in XCode are an excellent resource for testing things like this.
Swift
var arrName = [String]()
arrName = ["Deep", "Hemant", "Yash"]
print("old array--> ", arrName)
arrName.append("Jay")
print("new array--> ", arrName)
Output:-
old array--> ["Deep", "Hemant", "Yash"]
new array--> ["Deep", "Hemant", "Yash", "Jay"]