issues when Iterate Map with list as value using groovy - list

def map = new HashMap<String,List<String>>()
def list = new ArrayList<String>()
def list1 = new ArrayList<String>()
list.add("hello1")
list​.add("world1")
list.add("sample1")
list.add("sample1")​​​​​​​​​​​​​​​​​​​​​​​​
list1.add("hello2")
list1.add("world2")
list1.add("sample2")
list1.add("sample2")
map.put("abc",list)
map.put("bcd",list1)
def data = new ArrayList<String>()
for(e in map){
println "key = ${e.key} value=${e.value}"
// data = "${e.value} as String[]"
data = "${e.value}"
println "size ${data.size()} " --(B)
check(data)
​}
def check(input)
{
println "${input.size()}" ---(A)
for(item in input){
print "$item "​​​​​​​​​​​​​​​​​}
​}​
I have to pass string[] to another java function from this groovy script. so I am trying to read the array list and then convert it into String array. But the problem is when I assign {e.value} to variable data and try to get the size data.size() (both step (A) and (B) ). and the size is 34. It is counting each character not the word as whole from the list. I want to iterate over each word from the list. Kindly let me know how to resolve this problem.
sample output is
key = abc value=[hello1, world1, sample1, sample1]
size 34

Here is the groovified vesion of creating the map and accessing it:
def map = [abc:['hello1', 'world1','sample1', 'sample1'], bcd:['hello2', 'world2','sample2', 'sample2']]
map.collect{ println "key: ${it.key}, list: ${it.value}, and size: ${it.value.size()}" }
Output:
key: abc, list: [hello1, world1, sample1, sample1], and size: 4
key: bcd, list: [hello2, world2, sample2, sample2], and size: 4
If you want to convert a list to an array you can just do it:
def list = ['hello1', 'world1','sample1', 'sample1']
assert list instanceof List
def array = list as String[]
assert array instanceof String[]
assert !(array instanceof List)

Related

How to iterate through single <key, value> pairs of List in dart

I have 2 Lists (uid and url) that are growable, and I need to set the first List as the key and the second as value. At some point, i'll have a 3rd List (randomUids) which will be keys and will print out the corresponding values. Here is the example code:
List<String> uid = ["uid1", "uid2","uid3","uid4"]; //Lists will grow larger after a while
List<String> url = ["url1","url2","url3","url4"];
List<String> randomUids = ["uid4", "uid2"];
When I try:
Map<List, List> mapKeyValue = Map();
mapKeyValue[uid] = url;
print( uid.contains(randomUids));
I get a false. Also, the print returns uid and url Lists as 2 long indices instead of separate Strings. How can I iterate the List so that url.contains(randomUids) is true. Also how can I print out the values of randomUids.
When I try:
print( uid.contains(randomUids));
I get a false.
Your code asks if uid (a List of Strings) contains randomUids (another List of Strings). It returns false because uid's elements are not Lists; they're Strings.
Presuming that you want the nth element of uid to correspond to the nth element of url, and you can guarantee that uid.length == url.length, you can construct a Map of UIDs to URLs:
assert(uid.length == url.length);
var uidMap = <String, String>{
for (var i = 0; i < uid.length; i += 1)
uid[i]: url[i],
};
And then you can iterate over randomUids and do lookups:
for (var uid in randomUids) {
if (uidMap.containsKey(uid)) {
print(uidMap[uid]);
}
}

Python remove all numbers from a list

I have a list of unicode elements and I'm trying to remove all integer numbers from It.
My code is:
List = [u'123', u'hello', u'zara', u'45.3', u'pluto']
for el in List:
if isinistance(el, int):
List.remove(el)
The code doesn't work, It give me the same list with u'123' include.
What i need is this:
List = [ u'hello', u'zara', u'45.3', u'pluto']
Can somebody hel me?
You list consists of unicode strings which are no instances of int obviously. You can try converting them to int in a helper function and use this as a condition to remove them/ to construct a new list.
def repr_int(s):
try:
int(s)
return True
except ValueError:
return False
original_list = [u'123', u'hello', u'zara', u'45.3', u'pluto']
list_with_removed_ints = [elem for elem in original_list if not repr_int(elem)]

How do i extract specific characters from elements in a list in python?

['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
I have a list of string and i want to extract the 'name\n' part from each element and store it. For example i want to extract 'name\n' from mylist[0], where mylist[0] = 'PRE user_/n'. So user_1/ will be extracted and stored in a variable.
mylist = ['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
for x in mylist:
i = 0
userid = *extract the 'name\n' from mylist[i]
print userid
i = i+1
How do i do this? Is Regular Expressions the way to do it?, if yes how do i implement it? A code snippet would be very helpful.
Maybe you can do it without regex. You can try my solution:
a = ['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
def get_name(arg = ""):
b = arg.split(" ")
for i in b:
if "\n" in i:
return i.replace("\n", "")
Output:
print get_name(a[0])
user_1/
print get_name(a[1])
UserID-12345.jpg
print get_name(a[2])
anpr.jpg
print get_name(a[3])
image.jpg
Also in order to fill the example you gave, your code will be:
for x in a:
userid = get_name(x)
print userid
Output:
user_1/
UserID-12345.jpg
anpr.jpg
image.jpg

How to convert list of list to simple list by removing duplicate values using scala?

I have following list -
List(List(
List(((groupName,group1),(tagMember,["192.168.20.30","192.168.20.20","192.168.20.21"]))),
List(((groupName,group1),(tagMember,["192.168.20.30"]))),
List(((groupName,group1),(tagMember,["192.168.20.30","192.168.20.20"])))))
I want to convert it to -
List((groupName, group1),(tagMember,["192.168.20.30","192.168.20.20","192.168.20.21"]))
I tried to use .flatten but unable to form desired output.
How do I get above mentioned output using scala??
I had to make some changes to your input to make it valid.
Input List:
val ll = List(List(
List((("groupName","group1"),("tagMember", List("192.168.20.30","192.168.20.20","192.168.20.21")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20"))))
))
Code below works if the group, and tagMember are the same across all the elements in the list
def getUniqueIpsConstantGroupTagMember(inputList: List[List[List[((String, String), (String, List[String]))]]]) = {
// List[((String, String), (String, List[String]))]
val flattenedList = ll.flatten.flatten
if (flattenedList.size > 0) {
val group = flattenedList(0)._1
val tagMember = flattenedList(0)._2._1
val ips = flattenedList flatMap (_._2._2)
((group), (tagMember, ips.distinct))
}
else List()
}
println(getUniqueIpsConstantGroupTagMember(ll))
Output:
((groupName,group1),(tagMember,List(192.168.20.30, 192.168.20.20, 192.168.20.21)))
Now, let's assume you could have different groupNames.
Sample input:
val listWithVariableGroups = List(List(
List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20","192.168.20.21")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20")))),
List((("groupName","group2"),("tagMember",List("192.168.20.30","192.168.20.10"))))
))
The following code should work.
def getUniqueIpsForMultipleGroups(inputList: List[List[List[((String, String), (String, List[String]))]]]) = {
val flattenedList = inputList.flatten.flatten
// Map[(String, String),List[(String, List[String])]]
val groupedByGroupNameId = flattenedList.groupBy(p => p._1) map {
case (key, value) => (key, ("tagMember", extractUniqueTagIps(value)))
}
groupedByGroupNameId
}
def extractUniqueTagIps(list: List[((String, String), (String, List[String]))]) = {
val ips = list flatMap (_._2._2)
ips.distinct
}
getUniqueIpsForMultipleGroups(listWithVariableGroups).foreach(println)
Output:
((groupName,group1),(tagMember,List(192.168.20.30, 192.168.20.20, 192.168.20.21)))
((groupName,group2),(tagMember,List(192.168.20.30, 192.168.20.10)))

For loop to access dictionary

I have a NSDictionary of type String:AnyObject, and I want to have it be type String:String. How can I convert them with the same key to type string using a loop? I would think I could figure it out, but Xcode 6 sourcekit keeps crashing whenever I put in a for loop for the dictionary.
PS. I'm writing this in Swift, not Obj-C.
This way you can loop over the dictionary for objects:AnyObject:
let dict = ["A":1, "B":2, "C":3]
var string = ""
for object in dict.values {
string += "\(object)"
}
// string = "312"
If you want to loop over just the keys change to .keys as in the following:
for key in dict.keys {
string += key
}
// string = "CAB"
Finally to loop over both keys and values with a Tuple (key, object) :
let dict = ["A":1, "B":2, "C":3]
var string = ""
var sum = 0
for (key, object) in dict {
string += key
sum += object
}
// sum = 6
// string = "CAB"
Note: This works with Beta 3.