How to have and declare/define array of tuple[ string , seq[ array[2,string] ] ]
Illustration is
var
a : seq[tuple[ string , seq[array[ 2, string]] ] ]
a[0] = [ "foo", [ ["hello", "foo"], ["foo", "bar" ] ] ]
a[1] = [ "bar", [ ["hello", "world"], ["hello", bar"] ] ]
a[2] = [ "hello", [ ["foo","bar"], ["hello","world"], ["bar", "baz"] ] ]
.
.
.
a[n] =
Tried rather long in this variations, e.g.
a = newSeqOfCap[ (string, newSeqOfCap[ array[ 2, string]](40) ) ](9)
all just end with no avail
Please guide the correct way. Thanks in advance for sincere help
You need to use newSeq, not newSeqOfCap. The latter only allocates the space for the sequence, not actually put anything in there for you to modify.
var a = newSeq[(string, seq[array[2, string]])](n)
a[0] = ("foo", #[["hello", "foo"], ["foo", "bar"]])
a[1] = ("bar", #[["hello", "world"], ["hello", "bar"]])
a[2] = ("hello", #[["foo", "bar"], ["hello", "world"], ["bar", "baz"]])
.
.
.
a[n] = ...
Related
I want to concatenate a text and a number next after it in a list using python.My input lists are given below:
a= ["hello", "hello", "1", "hello", "2"]
b= ["hello", "hello", "1"]
c= ["hello", "1"]
my desired output :
a= ["hello", "hello 1", "hello 2"]
b= ["hello", "hello 1"]
c= ["hello 1"]
Can anyone suggest a solution?
You can try using regex from the re library. Also I advise to have a look at Regex 101 to build the regex you need and test it, to get an understanding on how they work
import re
a= ["hello", "hello", "1", "hello", "2"]
a = [i.replace(' ', '') for i in re.findall('\w+\s*\d*',' '.join(a))]
>>>print(a)
['hello', 'hello1', 'hello2']
I would like to replace pandas multi index columns with uppercase names. With a normal (1D/level) index, I would do something like
df.coulumns = [c.upper() for c in df.columns]
When this is done on a DataFrame with a pd.MultiIndex, I get the following error:
AttributeError: 'tuple' object has no attribute 'upper'
How would I apply the same logic to a pandas multi index? Example code is below.
import pandas as pd
import numpy as np
arrays = [
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)
arrays_upper = [
["BAR", "BAR", "BAZ", "BAZ", "FOO", "FOO", "QUX", "QUX"],
["ONE", "TWO", "ONE", "TWO", "ONE", "TWO", "ONE", "TWO"],
]
tuples_upper = list(zip(*arrays_upper))
index_upper = pd.MultiIndex.from_tuples(tuples_upper, names=['first', 'second'])
df_upper = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index_upper)
print(f'Have: {df.columns}')
print(f'Want: {df_upper.columns}')
You can convert the multiindex to dataframe and uppercase the value in dataframe then convert it back to multiindex
df.columns = pd.MultiIndex.from_frame(df.columns.to_frame().applymap(str.upper))
print(df)
first BAR BAZ FOO QUX
second ONE TWO ONE TWO ONE TWO ONE TWO
A -0.374874 0.049597 -1.930723 -0.279234 0.235430 0.351351 -0.263074 -0.068096
B 0.040872 0.969948 -0.048848 -0.610735 -0.949685 0.336952 -0.012458 -0.258237
C 0.932494 -1.655863 0.900461 0.403524 -0.123720 0.207627 -0.372031 -0.049706
Or follow your loop idea
df.columns = pd.MultiIndex.from_tuples([tuple(map(str.upper, c)) for c in df.columns])
Use set_levels:
df.columns = df.columns.set_levels([level.str.upper() for level in df.columns.levels])
mylist = ["apples", "bananas", "mangos"]
Wanted output:
"apples", "bananas", "mangos"
I've managed to print it this way but can't make it with apostrophes.
print(','.join([x for x in mylist]))
apples,bananas,mangos
You would need to add quotes to beginning and end, like this
print('"'+'", "'.join(mylist)+'"')
>>> mylist = ["apples", "bananas", "mangos"]
>>> print(', '.join(['"' + x + '"' for x in mylist]))
"apples", "bananas", "mangos"
>>> print(repr(mylist).strip('[]'))
'apples', 'bananas', 'mangos'
Ref: https://docs.python.org/3/library/functions.html#repr
I'm going to initialize a empty Map dynamically in a loop, i.e. key1 and key2 are variables in the loop:
Map<String, Map<String, List>> map = [
key1: [
key2: []
]
]
I'm trying initialize the map structure by getOrDefault in two ways. One (y) using the hardcode as key name, another (x) using the variable as the keyname:
Map y = [:]
Map x = [:]
String b = 'b'
String c = 'c'
y = y.getOrDefault( "b" , [ "b" : [:] ] )
.getOrDefault( "c" , [ "b" : [ "c" : []] ] )
x = x.getOrDefault( "${b}" , [ "${b}" : [:] ] )
.getOrDefault( "${c}" , [ "${b}" : [ "${c}" : []] ] )
However, when I try get result of map.b.c,
Map x:
x.get("${b}").get("${c}") : works
x["${b}"]["${c}"] : java.lang.NullPointerException
Map y works well in all various ways
println """
y['b']['c'] : ${y['b']['c']}
y.b.c : ${y.b.c}
y.get('b').get('c') : ${y.get('b').get('c')}
x.get("\${b}") : ${x.get("${b}")}
x["\${b}"] : ${x["${b}"]} // *why null*
x.get("\${b}").get("\${c}") : ${x.get("${b}").get("${c}")}
"""
println """ x["\${b}"]["\${c}"] : ${x["${b}"]["${c}"]} """
==> result
y['b']['c'] : []
y.b.c : []
y.get('b').get('c') : []
x.get("${b}") : [c:[]]
x["${b}"] : null // *why null*
x.get("${b}").get("${c}") : []
Exception thrown
java.lang.NullPointerException: Cannot get property 'c' on null object
at ConsoleScript77.run(ConsoleScript77:21)
I want to know why x.get("${b}").get("${c}") works, but x["${b}"]["${c}"] got null
btw, here the dynamic map initialization details:
Map m = [
'x' : [
'name': 'x',
'size': ['1', '2'],
'age': '1',
],
'y': [
'name': 'x',
'size': ['2', '3'],
'age': '2'
]
]
Map a = [:]
m.each{ k, v ->
v.size.each {
String t = "${v.name}-${it}"
a = a.getOrDefault(t, ["${t}": [:]])
println """
t: ${t}
k: ${k}
a: ${a}
a.t: ${a.t}
a.get("${t}"): ${a.get("${t}")}
a["${t}"]: ${a["${t}"]}
"""
}
}
=== output:
t: x-1
k: x
a: [x-1:[:]]
a.t: null
a.get("x-1"): [:]
a["x-1"]: null
t: x-2
k: x
a: [x-2:[:]]
a.t: null
a.get("x-2"): [:]
a["x-2"]: null
....
Appreciate #daggett.
So the truth is:
y.each { k, v ->
println """
key: ${k} \t\t\t key.getClass(): ${k.getClass()}
value: ${v} \t\t value.getClass(): ${v.getClass()}
"""
}
x.each { k, v ->
println """
key: ${k} \t\t\t key.getClass(): ${k.getClass()}
value: ${v} \t\t value.getClass(): ${v.getClass()}
"""
}
==> result
key: b key.getClass(): class java.lang.String
value: [c:[]] value.getClass(): class java.util.LinkedHashMap
key: b key.getClass(): class org.codehaus.groovy.runtime.GStringImpl
value: [c:[]] value.getClass(): class java.util.LinkedHashMap
So, according to my previous ${x["${b}"]}, the key of x ( "${b}" ) was type conversion to String, and x only has the key belongs to GStringImpl, so the result is null
However, .get("${b}") works, because of :
println "${b}".getClass() // class org.codehaus.groovy.runtime.GStringImpl
Here more details:
Map x = [:]
String str = 'a'
x = x.getOrDefault( "${str}", [ "${str}" : [:] ] )
x.each { k, v -> println "${k}: ${k.getClass()}" }
Map x = [:]
String str = 'a'
x = x.getOrDefault( "${str}", [ "${str}" : [:] ] )
x.each { k, v -> println "${k}: ${k.getClass()}" } // a: class org.codehaus.groovy.runtime.GStringImpl
assert x == [ "${s}" : [:] ]
assert x.a == null
assert x."${str}" == null
assert x["${str}"] == null
assert x[str] == null
assert x.get(str) == null
assert x.get("${str}") == [:]
I have a map where a key holds multiple values
datamap = [ 'Antenna Software':[ 'Salarpuria', 'Cessna', 'Vrindavan Tech', 'Alpha Center' ],
'Ellucian':[ 'Malvern', 'Ellucian House', 'Residency Road'] ]
here i need to alphabetically sort the values
datamap = [ 'Antenna Software':[ 'Alpha Center', 'Cessna', 'Salarpuria', 'Vrindavan Tech' ],
'Ellucian':[ 'Ellucian House', 'Malvern', 'Residency Road' ] ]
how to do it in groovy way?
You should be able to do:
def sortedMap = datamap.sort().collectEntries { k, v ->
[ k, v.sort( false ) ]
}
If you're not bothered about sorting the keys of the map, you can get rid of the initial sort():
def sortedMap = datamap.collectEntries { k, v ->
[ k, v.sort( false ) ]
}
Explanation of sort( false ):
By default, the sort method in Groovy changes the original list, so:
// Given a List
def a = [ 3, 1, 2 ]
// We can sort it
def b = a.sort()
// And the result is sorted
assert b == [ 1, 2, 3 ]
// BUT the original list has changed too!
assert a != [ 3, 1, 2 ] && a == [ 1, 2, 3 ]
So if you pass false to sort, it leaves the original list alone, and just returns the sorted list:
// Given a List
def a = [ 3, 1, 2 ]
// We can sort it (passing false)
def b = a.sort( false )
// And the result is sorted
assert b == [ 1, 2, 3 ]
// AND the original list has remained the same
assert a == [ 3, 1, 2 ]