Pulling a field from a list based on second list - groovy

I have the following lists:
list1 = [["value1":"name1", "value2":"check1"], ["value1":"name2", "value2":" check2"],
["value1":"name3", "value2":" check3"]]
list2 = ['name1', 'name2']
I would like to pull the list of all the "value2" for name1 and name2.
as:
[check1, check2]

This should do it:
def list3 = list1.findAll { it.value1 in list2 }.value2

def list1 = [["value1":"name1", "value2":"check1"], ["value1":"name2", "value2":" check2"],
["value1":"name3", "value2":" check3"]]
def list2 =list1.collect{it."value2"}

Related

How to get unique values in nested list along single column?

I need to extract only unique sublists based on first element from a nested list. For e.g.
in = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = [['a','b'], ['e','f'], ['g','h']]
My method is two break list into two lists and check for elements individually.
lis = [['a','b'], ['a','d'], ['e','f'], ['g','h']]
lisa = []
lisb = []
for i in lis:
if i[0] not in lisa:
lisa.append(i[0])
lisb.append(i[1])
out = []
for i in range(len(lisa)):
temp = [lisa[i],lisb[i]]
out.append(temp)
This is an expensive operation when dealing with list with 10,00,000+ sublists. Is there a better method?
Use memory-efficient generator function with an auziliary set object to filter items on the first unique subelement (take first unique):
def gen_take_first(s):
seen = set()
for sub_l in s:
if sub_l[0] not in seen:
seen.add(sub_l[0])
yield sub_l
inp = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = list(gen_take_first(inp))
print(out)
[['a', 'b'], ['e', 'f'], ['g', 'h']]

Mistake in list comprehension

Problem Solved!
I have two python lists of integers that are randomly generated. I want to find the numbers that are common between the lists.
Using list comprehension, I've come up with this:
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
However, this returns an empty list. I have a working program using loops that works perfectly:
for a in list_one:
for b in list_two:
if a == b and a not in new_list:
new_list.append(a)
What mistakes have I made converting it to a list comprehension?
This is a simple approach with sets,
list_1 = [1,2,3,4,5]
list_2 = [5,4,7,7,5,1,2,8,9]
new_list = list(set(list_1) & set(list_2))
print(new_list)
It uses the set intersection has a number of benefits compared to a list comprehension:
The input lists do not need to be sorted (though you can sort them by using sorted() function.
The input lists can have different lengths.
Presence of duplicates is taken care of automatically (sets don't admit those).
I do not think list comprehension is required for intersection of 2 lists.
Anyways you can modify your code to-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
print(new_list)
you can also do-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one if a in list_two and a not in new_list]
print(new_list)
You can convert it into set and use set1.intersection(set2).
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = list(set(list_one).intersection(set(list_two)))
print(new_list)
You can't reference the same list inside of a list comprehension.
Thanks #Keith from the comments of the OP for pointing it out.

Convert list elements to list values of another list

I am trying to convert list elements of a given list to list value of another list. Here is an example:
list1 = ['apple', 'tomato', 'milk', 'beans', 'mango']
list2 = [{0,4}, {1,3}, 2]
result = []
expected output:
[{'apple', 'banana'}, {'tomato', 'beans'}, 'milk']
I am trying to use the below code, but it does not work:
for i in list2:
result.append(list1[i])
Assuming list2 will only contain set, list, or int. This would be my approach.
list1 = ['apple', 'tomato', 'milk', 'beans', 'mango']
list2 = [{0,4}, {1,3}, 2]
result = []
# [{'apple', 'banana'}, {'tomato', 'beans'}, 'milk']
for x in list2:
temp_lst = []
if type(x) in [set, list]:
new_set = set()
for y in x:
new_set.add(list1[y])
temp_lst.append(new_set)
else:
temp_lst.append(list1[x])
result.extend(temp_lst)
print(result)

return dictionary of file names as keys and word lists with words unique to file as values

I am trying to write a function to extract only words unique to each key and list them in a dictionary output like {"key1": "unique words", "key2": "unique words", ... }. I start out with a dictionary. To test with I created a simple dictionary:
d = {1:["one", "two", "three"], 2:["two", "four",
"five"], 3:["one","four", "six"]}
My output should be:
{1:"three",
2:"five",
3:"six"}
I am thinking maybe split in to separate lists
def return_unique(dct):
Klist = list(dct.keys())
Vlist = list(dct.values())
aList = []
for i in range(len(Vlist)):
for j in Vlist[i]:
if
What I'm stuck on is how do I tell Python to do this: if Vlist[i][j] is not in the rest of Vlist then aList.append(Vlist[i][j]).
Thank you.
You can try something like this:
def return_unique(data):
all_values = []
for i in data.values(): # Get all values
all_values = all_values + i
unique_values = set([x for x in all_values if all_values.count(x) == 1]) # Values which are not duplicated
for key, value in data.items(): # For Python 3.x ( For Python 2.x -> data.iteritems())
for item in value: # Comparing values of two lists
for item1 in unique_values:
if item == item1:
data[key] = item
return data
d = {1:["one", "two", "three"], 2:["two", "four", "five"], 3:["one","four", "six"]}
print (return_unique(d))
result >> {1: 'three', 2: 'five', 3: 'six'}
Since a key may have more than one unique word associated with it, it makes sense for the values in the new dictionary to be a container type object to hold the unique words.
The set difference operator returns the difference between 2 sets:
>>> a = set([1, 2, 3])
>>> b = set([2, 4, 6])
>>> a - b
{1, 3}
We can use this to get the values unique to each key. Packaging these into a simple function yields:
def unique_words_dict(data):
res = {}
values = []
for k in data:
for g in data:
if g != k:
values += data[g]
res[k] = set(data[k]) - set(values)
values = []
return res
>>> d = {1:["one", "two", "three"],
2:["two", "four", "five"],
3:["one","four", "six"]}
>>> unique_words_dict(d)
{1: {'three'}, 2: {'five'}, 3: {'six'}}
If you only had to do this once, then you might be interested in the less efficeint but more consice dictionary comprehension:
>>> from functools import reduce
>>> {k: set(d[k]) - set(reduce(lambda a, b: a+b, [d[g] for g in d if g!=k], [])) for k in d}
{1: {'three'}, 2: {'five'}, 3: {'six'}}

How to concatenate 2 list strings using list comprehension

I have 2 lists as below:
list1 = ['A','B']
list2 = ['C','D']
The required output should be [['AC','BC'], ['AD','BD']] using List comprehension.
Using two for loops as a list comprehension
list1= ['A','B']
list2= ['C','D']
b=[[l+p for l in list1] for p in list2]
print(b)

Resources