I have a list [ a , b , c , b , d]
I want to remove a c and d, while keeping both of the b's.
How do I do this?
I want my end list to be [ b , b ]
#Yodrangonface, this is for Python version:
from collections import Counter
lst = ['a', 'b', 'c', 'b', 'd']
duplicates = [k for k, v in Counter(lst).items() if v >= 2]
duplicates
Output:
['b']
This depend on which programming langage your are using.
For instance in java you could handle it that way:
List<String> duplicateList = new ArrayList<>();
duplicateList.add("Cat");
duplicateList.add("Dog");
duplicateList.add("Cat");
duplicateList.add("cow");
duplicateList.add("Dog");
duplicateList.add("Cow");
duplicateList.add("Goat");
Set<String> duplicated = duplicateList
.stream()
// Grouping by number of occurrences
.collect(Collectors.groupingBy(e -> e.toString(),Collectors.counting()))
.entrySet()
// Filtering of item with more than one occurrence
.stream().filter(item->item.getValue()>1)
.collect(Collectors.toMap(item -> item.getKey(), map -> map.getValue()))
.keySet();
System.out.println(duplicated);
List<String> remaining = duplicateList.stream().filter(item->duplicated.contains(item)).collect(Collectors.toList());
System.out.println(remaining);
output is:
[Cat, Dog]
[Cat, Dog, Cat, Dog]
Related
I am trying to tie two different things together.
1. Find and print unique items in a list.
2. Pass a int value and print unique items in the first n items
I have two things that work, but not in conjunction, to split the list into sub-lists of n:
def find_uniques(3):
lista = ['a', 'a', 'b','c','d','c','e','d','e','f','f']
lists = [lista[x:x+n] for x in xrange(0, len(lista), n)]
print lists
[['a', 'a', 'b'], ['c', 'd', 'c'], ['e', 'd', 'e'], ['f', 'f']]
# 2nd part works on the whole list
print [a for a in lista if lista.count(a) == 1]
['b']
# How do I get the second part to work on the sub lists, and give me back unique chars from each sub list.
The output I am looking for:
[['b'],['d'], ['d']]
Usually it is easier to just split out these operations instead of merging, but here is a nested list comprehension.
lista = ['a', 'a', 'b','c','d','c','e','d','e','f','f']
n = 3
[[ item for item in sublist if sublist.count(item) == 1] for sublist in [ lista[x:x+n] for x in xrange(0, len(lista), n) ] ]
Personally, although it is longer, I prefer a more readable version like so:
def findunique(lista,n=3):
listoflists = [ lista[x:x+n] for x in xrange(0,len(lista),n) ]
results = []
for sublist in listoflists:
unique = [ item for item in sublist if sublist.count(item) == 1]
if unique:
results.append(unique)
return results
lista = ['a','a','b','c','d','c','e','d','e','f','f']
print findunique(lista,3)
del rec[1][1]
Is this the way to delete an item from a list of lists???
[ ['a','b','c'],
['d','e','f'],
['g','h','i'] ]
I want to delete b, e and h. How should I do that???
You can remove 'b', 'e' and 'h' by doing this
# the main list of lists
list1 = [ ['a','b','c'], ['d','e','f'],['g','h','i'] ]
for x in xrange(len(list1)):
del_list = list1[x][1]
while del_list in list1[x]: list1[x].remove(del_list)
print((list1))
Output
[['a', 'c'], ['d', 'f'], ['g', 'i']]
This was easy since the entries were exactly at the 2nd positions of the sublists of list1.
You could use .pop(i) method, where 'i' is an iterator.
rec = [ ['a','b','c'],
['d','e','f'],
['g','h','i'] ]
for i in range (0, len(rec)):
print rec[i].pop(1)
Note that .pop() method also returns that item.
The above code will result in :
b
e
h
I have two lists that I need to merge into a new list, but the new list needs to contain merged indexes of the original lists. For example:
List1 = [1, 2, 3]
List2 = [a, b, c]
I need the output to be:
finalList = [1a, 2b, 3c]
I need to be able to do this in groovy. I appreciate any help you can provide.
Assuming both lists are the same size, in Groovy 2.4+,
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
assert ['1a', '2b', '3c'] == list1.withIndex().collect { it, index -> it + list2[index] }
Alternatively and a bit more simply in Groovy 1.5+,
assert ['1a', '2b', '3c'] == [list1, list2].transpose()*.sum()
The following is very close to doelleri's solution:
In Groovy 2.4+
println ([list1, list2].transpose().collect{it -> it[0] + it[1]})
OUTPUT
[1a, 2b, 3c]
I'm trying to understand how comprehensions work.
I would like to loop through two lists, and compare each to find differences.
If one/or-more word(s) is different, I would like to print this word(s).
I'd like this all in one nice line of code, which is why I'm interested in comprehensions.
Doing it in "one nice line of code" is code golf, and misguided. Make it readable instead.
for a, b in zip(list1, list2):
if a != b:
print(a, "is different from", b)
This is not different in any significant way from this:
[print(a, "is different from", b) for a, b in zip(list1, list2) if a!=b]
Except that the expanded version easier to read and understand than the comprehension.
Like kriegar suggested using sets is probably the easiest solution. If you absolutely need to use list comprehension, I'd use something like this:
list_1 = [1, 2, 3, 4, 5, 6]
list_2 = [1, 2, 3, 0, 5, 6]
# Print all items from list_1 that are not in list_2 ()
print(*[item for item in list_1 if item not in list_2], sep='\n')
# Print all items from list_1 that differ from the item at the same index in list_2
print(*[x for x, y in zip(list_1, list_2) if x != y], sep='\n')
# Print all items from list_2 that differ from the item at the same index in list_1
print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n')
If you want to compare two lists for differences, I think you want to use a set.
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
example:
>>> L1 = ['a', 'b', 'c', 'd']
>>> L2 = ['b', 'c', 'd', 'e']
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> difference = list(S1.symmetric_difference(S2))
>>> print difference
['a', 'e']
>>>
one-line form?
>>> print list(set(L1).symmetric_difference(set(L2)))
['a', 'e']
>>>
if you really want to use a list comprehension:
>>> [word for word in L1 if word not in L2] + [word for word in L2 if word not in L1]
['a', 'e']
much less efficient as the size of the lists grow.
Suppose I have two lists:
val a = List('a', 'b', 'c')
val b = List('a', 'b', 'c', 'd')
I want to get the element which is not in the first list (in this case it's 'd'). I know I can do this with a loop, but is there any fancy functional way to do this quickly in one line?
I've been looking at the Scala List API, but could only found union and intersection (which will give me List('a', 'b', 'c', 'd') and List('a', 'b', 'c') respectively)
You can use diff for this:
scala> b diff a
res1: List[Char] = List(d)
You probably want to work with Set if you are doing diff.
I think you can use b -- a. Here is the documentation from scala:
def -- [B >: A] (that: List[B]) : List[B]
Computes the difference between this list and the given list that.
that
the list of elements to remove from this list.
returns this list without the elements of the given list that.
deprecated: use list1 filterNot (list2 contains) instead
Sorry for the deprecated method, here is the current good one: list1 filterNot (list2 contains)
def filterNot (p: (A) ⇒ Boolean) :
List[A] Selects all elements of this
list which do not satisfy a predicate.
p the predicate used to test elements.
returns a new list consisting of all
elements of this list that do not
satisfy the given predicate p. The
order of the elements is preserved.
definition classes: TraversableLike
Of course, this can be done in many ways. For flat structures like list of numbers and strings diff is the most elegant. Other ways are,
val ans1 = for { x <- b if !a.contains(x) } yield x
val ans2 = for { x <- b if !a.exists(_ == x) } yield x
val ans3 = b filterNot (x => b.contains(x) )
val ans4 = b diff a