Groovy lists and maps - list

i am writing my helper methods for selenium tests. One of them is :
private static List<DataRow> parseTable(WebElement table) {
List<WebElement> tableHeaders = table.findElements(By.tagName("th"))
List<DataRow> dataRow = table.findElements(By.xpath(".//tbody/tr")).collect {
Map<String, String> columns = [:]
it.findElements(By.tagName("td")).eachWithIndex { item, i ->
columns[tableHeaders.get(i).text] = item.text
}
new DataRow(it, columns)
}
return dataRow
}
And i dont like this part:
it.findElements(By.tagName("td")).eachWithIndex { item, i ->
columns[tableHeaders.get(i).text] = item.text
}
Is there a better way to make map from two lists?

You should be able to do:
def columns = [tableHeaders,it.findElements(By.tagName("td"))].transpose().collectEntries()
By way of an explanation:
Given:
def a = [ 'a', 'b', 'c' ]
def b = [ 1, 2, 3 ]
Then
def c = [ a, b ].transpose()
assert c == [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
And:
def d = c.collectEntries()
assert d instanceof Map
assert d == [ a:1, b:2, c:3 ]

Related

Dart: How to get total length of all list values in a list of map?

I have this:
final data = [
{
'name': 'Team A',
'team': ['Klay Lewis', 'Ehsan Woodard', 'River Bains']
},
{
'name': 'Team B',
'team': ['Toyah Downs', 'Tyla Kane']
},
{
'name': 'Team C',
'team': [
'Jacky Chan',
'Yalor Rowds',
'Tim Bourla',
'Levis Strauss',
'Jane Smow'
]
}
];
I want to find the quickest way to get a sum of all team members. In the above example, it would be 3 + 2 + 5 = 10 total members.
The real world data will have thousands of teams, so quickest way needed.
fold will get the job done.
final int totalLength = data.fold(0, (sum, obj) => sum + obj['team'].length);
import 'package:collection/collection.dart';
const data = [...];
void main(List<String> args) {
var members = data.map((e) => (e['team'] as List).length).sum;
print(members);
}

how to extract data inside the list of maps and convert it into maps in dart

How can extract data inside the list of maps and convert it into maps in the dart.
Like I have a List of maps ================================================================================================================================================================================================
[
{"business_id":"2",
"business_title":"Spotify",
"business_phone":"(055) 3733783",
"business_email":"Usamashafiq309#gmail.com",
"business_website":"www.spotify.com",
"business_address":"Spotify AB, Regeringsgatans bro, Stockholm, Sweden",
"business_address_longitude":"18.0680873",
"business_address_latitude":"59.33096949999999",
"business_image":"5f84c7a4bbbd0121020201602537380.png",
"business_created_at":"2020-10-20 15:40:17",
"business_category_id":"2",
"cat_id":"2",
"cat_title":"Gym",
"cat_image":"280920201601308237.png"}
,{"business_id":"2",
"business_title":"Spotify",
"business_phone":"(055) 3733783",
"business_email":"Usamashafiq309#gmail.com",
"business_website":"www.spotify.com",
"business_address":"Spotify AB, Regeringsgatans bro, Stockholm, Sweden",
"business_address_longitude":"18.0680873",
"business_address_latitude":"59.33096949999999",
"business_image":"5f84c7a4bbbd0121020201602537380.png",
"business_created_at":"2020-10-20 15:40:17",
"business_category_id":"2",
"cat_id":"2",
"cat_title":"Gym",
"cat_image":"280920201601308237.png"}
]
and convert it like this
[ {"business_id":"2",
"business_title":"Spotify",},
{"business_id": "1",
"business_title": "Pizza Hut",},
]
You can use the map function to apply a function to each element of a list. Then you can create a submap with your map.
Here is a quick exemple:
void main() async {
List l = [
{
"business_id": "2",
"business_title": "Spotify",
"business_phone": "(055) 3733783",
},
{
"business_id": "1",
"business_title": "Pizza Hut",
"business_phone": "(055) 9999999",
}
];
print(extractMap(l));
}
List extractMap(List l) {
return l
.map((element) => Map.fromEntries([
MapEntry('business_id', element['business_id']),
MapEntry('business_title', element['business_title']),
]))
.toList();
}

Dart/Flutter - Compare two List<dynamic> if they have the same value of id

I have two List<dynamic> and I am trying to figure out how I can check if there is a same value in the id field
List list1 = [
{"id": 2, "name": "test1"},
{"id": 3, "name": "test3"}
];
List list2 = [
{"id": 2, "name": "test1"}
];
I tried this but it returns me false
var isMatch = (list1.toSet().intersection(list2.toSet()).length > 0);
You can not compare like that because you can't compare dynamic as Boken said, you need to create a class for your object and implement a basic search , you can convert list2 into a set to make the search less complex (contains function)
void main() {
List list1 = [
MyObject(2,"test"),
MyObject(3,"test1")
];
List list2 = [
MyObject(4,"test")
];
for(int i=0;i<list1.length;i++){
if(list2.contains(list1[i])){
// do your logic
print(true);
break;
}
}
}
class MyObject{
int id;
String name;
MyObject(int id,String name){
this.id = id;
this.name = name;
}
// redifine == operator
bool operator ==(o) => (o as MyObject).id == this.id;
}

Incrementing list values

I have a player template that I am copying, setting a field, and then appending the updated template to a new list.
player_template = {
"player": "",
"hand": [
{0 :
{
"cards_in_hand": [],
"cards_taken": []
}
}
]
}
However, when I go to do a range loop to create multiple players, it only creates the last player multiple times.
for i in range(4):
p["player"] = i
players.append(p)
Output:
[
{
'player': 3,
'hand': [
{
0: {
'cards_in_hand': [],
'cards_taken': []
}
}
]
},
{
'player': 3,
'hand': [
{
0: {
'cards_in_hand': [],
'cards_taken': []
}
}
]
},
{
'player': 3,
'hand': [
{
0: {
'cards_in_hand': [],
'cards_taken': []
}
}
]
},
{
'player': 3,
'hand': [
{
0: {
'cards_in_hand': [],
'cards_taken': []
}
}
]
}
]
I've tried range(start, stop, step), but it also produces the same results. How can I get the output to be player 1, player 2, etc.?
Currently you're overriding the previous player with each iteration. This is because dictionaries are mutable objects and you're poinging to the same one.
You need to deep-copy the mapping that represents a player:
import copy
for i in range(4):
p["player"] = i
players.append(copy.deepcopy(p))
I've used copy.deepcopy but you can do this manually if you want.
A better way would be to use an actual class to reperesent a Player.

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'