Get List of specific Values form List of Maps in Kotlin - list

I have a Kotlin list, which consists of Maps:
allData =
[
{
"a":"some a Data1",
"b":"some b Data1",
"c":"some c Data1"
},
{
"a":"some a Data2",
"b":"some b Data2",
"c":"some c Data2"
},
{
"a":"some a Data3",
"b":"some b Data3",
"c":"some c Data3"
}
]
Now I would like to get the List of all b-Data:
bData = ["some b Data1", "some b Data2", "some b Data3"]
How can I get bData from allData?

You can do
val bData = allData.map { it["b"] }
full example:
val allData = listOf(
mapOf("a" to "some a Data1", "b" to "some b Data1", "c" to "some c Data1"),
mapOf("a" to "some a Data2", "b" to "some b Data2", "c" to "some c Data2"),
mapOf("a" to "some a Data3", "b" to "some b Data3", "c" to "some c Data3")
)
val bData = allData.map { it["b"] }
print(bData )
//[some b Data1, some b Data2, some b Data3]

val allData = listOf(mapOf("a" to "some a Data1", "b" to "some b Data1", "c" to "some c Data1"), mapOf("a" to "some a Data2", "b" to "some b Data2", "c" to "some c Data2"), mapOf("a" to "some a Data3", "b" to "some b Data3", "c" to "some c Data3"))
val result = allData.map { it["b"] }

Related

Printing the most frequent value in a text

Let's say I have a list of string.
I saw the code on: How to count items' occurence in a List
I want to print the most frequent string as a text in my widget. How do i run this and print it in there?
Do i go by void main() ?
class user with ChangeNotifier {
static String topWord;
notifyListeners();
}
void countWord() {
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var popular = Map();
elements.forEach((element) {
if(!popular.containsKey(element)) {
popular[element] = 1;
} else {
popular[element] +=1;
}
});
print(popular);
return user.topWord = popular;
}
Attached are some screenshots when I return the results
Here you can first create the map of your counted values and then using that map you can get the maximum value of the key.
Source Here
class HomePage extends StatelessWidget {
String email;
var maxocc = maxOccurance();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("App Bar"),
),
body: Center(
child: Container(
child: Text(maxocc),
),
),
);
}
}
String maxOccurance() {
var elements = [
"a",
"b",
"c",
"d",
"e",
"a",
"b",
"c",
"f",
"g",
"h",
"h",
"h",
"e"
];
// Here creating map of all values and counting it
final folded = elements.fold({}, (acc, curr) {
acc[curr] = (acc[curr] ?? 0) + 1;
return acc;
}) as Map<dynamic, dynamic>;
print(folded);
// Here getting maximum value inside map
final sortedKeys = folded.keys.toList()
..sort((a, b) => folded[b].compareTo(folded[a]));
return "${sortedKeys.first} occurs maximun times i.e. ${folded[sortedKeys.first]}";
}
Output Here

Concatenate lists with Python

I would like to concatenate two lists:
list_a = ["hello", "world"]
list_b = ["a", "b", "c", "d"]
and get something like this as output:
list_c = ["hello a", "hello b", "hello c", "hello d", "world a", "world b", "world c", "world d"]
The second list is basically going from a to z and create combinations with the list_a.
from functools import reduce
list_a = ["hello", "world"]
list_b = ["a", "b", "c", "d"]
def cross_join_lists(word):
return [f'{word} {letter}' for letter in list_b]
def concat_lists(final_list, a_list):
return final_list + a_list
joined_lists = list(map(cross_join_lists, list_a))
list_c = reduce(concat_lists, joined_lists)
print(list_c)
You can use a list comprehension:
new_list = [f"{i} {j}" for i in list_a for j in list_b]
# output: ['hello a', 'hello b', 'hello c', 'hello d', 'world a', 'world b',
'world c', 'world d']

How to count items' occurence in a List

I am new to Dart. Currently I have a List of duplicate items, and I would like to count the occurence of them and store it in a Map.
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
I want to have a result like:
{
"a": 3,
"b": 2,
"c": 2,
"d": 2,
"e": 2,
"f": 1,
"g": 1,
"h": 3
}
I did some research and found a JavaScript solution, but I don't know how to translate it to Dart.
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
Play around with this:
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var map = Map();
elements.forEach((element) {
if(!map.containsKey(element)) {
map[element] = 1;
} else {
map[element] += 1;
}
});
print(map);
What this does is:
loops through list elements
if your map does not have list element set as a key, then creates that element with a value of 1
else, if element already exists, then adds 1 to the existing key value
Or if you like syntactic sugar and one liners try this one:
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var map = Map();
elements.forEach((x) => map[x] = !map.containsKey(x) ? (1) : (map[x] + 1));
print(map);
There are many ways to achieve this in all programming languages!
The shorter way to count items' occurrence in a List
List of items. Count items equal 1.
List<int> lst = [0,1,1,1,0,8,8,9,1,0];
int res = lst.map((element) => element == 1 ? 1 : 0).reduce((value, element) => value + element);
List of objects. Count objects, which property age equals 1.
class Person {
int age;
Person(this.age);
}
List<Person> lst2 = [Person(1), Person(0), Person(1), Person(0)];
int res2 = lst2.map((element) => element.age == 1 ? 1 : 0).reduce((value, element) => value + element);
Use fold with a map:
final elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
var counts = elements.fold<Map<String, int>>({}, (map, element) {
map[element] = (map[element] ?? 0) + 1;
return map;
});
print(counts);
Out: {a: 3, b: 2, c: 2, d: 1, e: 2, f: 1, g: 1, h: 3}

search and replace regex for JSON string

I have a JSON string of some object.
I want to
remove all the keys,
replace each and every key with 'alpha'
at any parent child level or at any child, throughout the whole object with the condition that if key start with 'a' and ends with 'z'.
For example :
i have json string :
"{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e", "awefz" : { "l" : "c" } } }, "c" : { "abcz" : "here" } }"
after applying regex 1) should get :
"{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e" } }, "c" : {} }"
after applying regex 2) should get :
"{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e", "alpha" : { "l" : "c" } } }, "c" : { "alpha" : "here" } }"
I am just looking for those regexes.
I need have only JSONString and regex(to be found) as inputs.
I do not want to loop through keys or recursive loops through levels.
I only want to achieve using regex over JSON string.
Is there any workaround?
regex 1:
,?\s*"a[^"]*z"\s*:[^}]+
replace with : ''
output :
"{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e"} } }, "c" : {} }"
demo : http://regex101.com/r/rO0yN0
regex 2:
a[^"]*z
replace with : alpha
output :
"{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e", "alpha" : { "l" : "c" } } }, "c" : { "alpha" : "here" } }"
demo : http://regex101.com/r/wB0rC9
I think this is the regex you want:
"a[^"]*z"\s*:
For JSON:
{{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e", "awefz" : { "l" : "c" } } }, "c" : { "abcz" : "here" } }
you will get:
{{ "a" : { "b" : 4 }, "b" : { "c" : { "d" : "e", "alpha": { "l" : "c" } } }, "c" : { "alpha": "here" } }
http://regex101.com/r/jV0qH0
Update
As for the other regex you want (removing the keys and values) - I'm afraid it is not possible, since JSON values cannot be expressed as a regular expression (they have balanced curly braces, which cannot be expressed as a regular expression), so you will have to find some other way of doing it.

Can Python edit individual list items?

I wrote a program that selects random words from lists to make a sentence. I want to write grammar rules for this. Right now I am working on plurals.
I want to add an s or es to the end of the selected word in 'nouns' if the word "those" is selected from list5.
import random
class Wrds(object):
verbs = [
"walk", "run"
]
pronouns = [
"I", "you"
]
help_verbs = [
"will", "might"
]
nouns = [
"boy", "girl"
]
list5 = [
"the", "that", "this", "a", "those"
]
punctuation = [
".", "?", "!"
]
def result(self):
a = random.choice(Wrds.verbs)
b = random.choice(Wrds.pronouns)
c = random.choice(Wrds.help_verbs)
d = random.choice(Wrds.nouns)
e = random.choice(Wrds.list5)
f = random.choice(Wrds.punctuation)
print "%s %s %s %s %s%s" % (b, c, a, e, d, f)
def ask():
a = raw_input("> ")
if a == "go":
w = Wrds()
return w.result()
elif a == "exit":
exit()
while True:
ask()
Before the print statement in the result method, add:
if e == 'those':
d += 's'