python common list of values from two lists - python

a = [1, 2, 4]
b = [9, 2,2,2,3,3, 4,4]
c= set(a) & set(b)
print(c)
Result : {2, 4}
i need it like : {2,2,2,4,4}
Thank you

If you'd like the duplicates in the result to correspond to the duplicates in b.
(as in your example)
c= [i for i in b if i in a]
output:
[2, 2, 2, 4, 4]

Related

Find common values in multiple lists [duplicate]

This question already has an answer here:
Get common values out of a list in python
(1 answer)
Closed 3 years ago.
So I have lists of numbers, and I would like to find numbers that exist in all the lists. I prefer not to use loop if possible.
Here is one example
a = [1, 2, 3, 4]
b = [2, 3, 4, 5, 6]
c = [3, 4, 5, 6, 10, 12]
df['A'] = [a, b, c]
The output is expected to be
[3, 4]
My problem here is, the number of lists is not given and not fixed. It can be about 20 lists with different lengths (e.g. [a, b, c, d, e, g, ..., l])
I have seen answers using set(a) & set(b) & set(c), but I am not sure how to apply this in my case.
You could use map along with set.intersection:
>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5, 6]
>>> c = [3, 4, 5, 6, 10, 12]
>>> elements_in_all = list(set.intersection(*map(set, [a, b, c])))
>>> elements_in_all
[3, 4]
I'm not sure why you'd want to avoid loops, since that's .. really what you're asking for - looping over a list of lists and keeping the set of unique values.
l = [a, b, c]
s = None
for e in l:
if not s:
s = set(e)
else:
s &= set(e)
s => set([3, 4])
You can also create a functional version that doesn't explicitly use loops, and still support an arbitrary number of arguments:
reduce((lambda x,y: x & y), map(set, l))
First, convert every list in your containing list l to a set, then use reduce to apply the intersection for each element contained - the result is a single set with the elements common to all lists.
In [29]: a = [1, 2, 3, 4]
...: b = [2, 3, 4, 5, 6]
...: c = [3, 4, 5, 6, 10, 12]
In [31]: a, b, c = map(set, (a,b,c))
In [32]: a.intersection(b,c)
Out[32]: {3, 4}

Python - How to extract numbers in list A depending on list B?

My purpose is:
For every element in B, I want to create a list, in which it contains elements of list B and smaller elements(than B element) in list A.
I tried two for loops, however, I do not know how to finish this work :
A=[1,2,3,4,5,6,7,8,9]
B=[3,4,5]
C=[]
for i in B:
for r in A:
if i>=r:
C.append(r)
I expect a result like this:
[[3,1,2,3],[4,1,2,3,4],[5,1,2,3,4,5]]
Any suggestions?
Try this:
for i in B:
new_list = [i] # inner list starting with the elmt from B
for r in A:
if i >= r:
new_list.append(r) # append to inner list
C.append(new_list) # finally append inner list to C
Have you tried using an array inside one of the loops:
A=[1,2,3,4,5,6,7,8,9]
B=[3,4,5]
C=[]
for b in B:
c = [b]
for a in A:
if a <= b:
c.append(a)
C.append(c)
print(C)
If you wanted to write this in one line:
A=[1,2,3,4,5,6,7,8,9]
B=[3,4,5]
C=[[b] + [a for a in A if a <= b] for b in B]
print(C)
prints
[[3, 1, 2, 3], [4, 1, 2, 3, 4], [5, 1, 2, 3, 4, 5]]
One solution could be following :
try:
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
B = [3, 4, 5]
D = []
a = sorted(A)
for b in B:
temp = [b]
temp.extend(a[0: a.index(b) + 1])
D.append(temp)
print(D)
except ValueError as e:
pass # Do something when value in B not found in a
You could use filter and list comprehension for one line operation
print [[i]+filter(lambda x: x <= i, A) for i in B]
results in
[[3, 1, 2, 3], [4, 1, 2, 3, 4], [5, 1, 2, 3, 4, 5]]
Here is your code
A=[1,2,3,4,5,6,7,8,9]
B=[3,4,5]
res=list()
for i in B:
C=list()
C.append(i)
for r in range(0,i):
C.append(A[r])
res.append(C)
print res,

function of difference between value

Is there a function in Python to get the difference between two or more values in a list? So, in those two lists:
list1 = [1, 5, 3, 7]
list2 = [4, 2, 6, 4]
I need to calculate the difference between every value in list1 and list2.
for i in list1:
for ii in list2:
print i -ii
This gives negative values, but I want the subtraction between the values of the two lists only from highest value to lowest value for not getting negative values.
For the above lists, I expect the output to be [3, 3, 3, 3].
Thanks.
Assuming you expect [3, 3, 3, 3] as the answer in your question, you can use abs and zip:
[abs(i-j) for i,j in zip(list1, list2)]
Either zip the lists, or use numpy:
>>> list1 = [1, 5, 3, 7]
>>> list2 = [4, 2, 6, 4]
>>> [a-b for a,b in zip(list1, list2)]
[-3, 3, -3, 3]
>>> import numpy as np
>>> np.array(list1) - np.array(list2)
array([-3, 3, -3, 3])
Remember to cast the array back to a list as needed.
edit:
In response to the new requirement that the absolute values are needed: you can add abs in the list comprehension:
>>> [abs(a-b) for a,b in zip(list1, list2)]
[3, 3, 3, 3]
and the numpy solution would change to:
>>> map(abs, np.array(list1) - np.array(list2))
[3, 3, 3, 3]
You may also do if else condition inside list comprehension.
>>> [i-j if i>j else j-i for i,j in zip(list1, list2)]
[3, 3, 3, 3]
You can use zip method in order combine these two lists. See the tutorials for zip method https://docs.python.org/2/library/functions.html#zip
>>> list1 = [1, 5, 3, 7]
>>> list2 = [4, 2, 6, 4]
>>> [abs(x-y) for x, y in zip(list1, list2)]
[3, 3, 3, 3]
Avinash Raj's answer is correct, or alternatively, using map():
from operator import sub
C = map(sub, A, B)

Deleting duplicates in list of lists in Python 2.7

Trenutno_stanje is list
povijest is list of lists
epsilon_okolina is function that gives list for a string (pocetno):
trenutno_stanje.append(pocetno)
trenutno_stanje.extend(epsilon_okolina[pocetno])
povijest.append(trenutno_stanje)
povijest should be essentialy list of lists, but it somehow in code duplicates entities
in a way it can be avoided.
What I would like to know is how to remove duplicate of strings in lists of a list?
I tried:
for p in povijest:
p=list(set(p))
But it changed nothing
In your for loop you are just reassigning p and not actually changing the povijest list. Also, set only works on hashable types, and list certainly is not one. You want to use list comprehension after you cast the lists inside the main list into something that can be hashed (like a tuple, which is an immutable list) and then turn that into a set.
>>> a = [1, 2, 3, 4]
>>> b = [1, 2, 3, 4]
>>> c = [1, 3, 4]
>>> i1 = [a, b, c]
>>> set([tuple(x) for x in i1])
set([(1, 2, 3, 4), (1, 3, 4)])
>>> b = [[1,2,3, 3], [3, 2, 4,4]]
>>> b = [ list(set(x)) for x in b ]
>>> b
[[1, 2, 3], [2, 3, 4]]
If you curious about the order try this ,
>>> a=[1,2,3,4,5]
>>> b=[2,3,1,2]
>>> c=[1,2,3,4,5]
>>> z=[a,b,c]
>>> dict((x[0], x) for x in z).values()
[[1, 2, 3, 4, 5], [2, 3, 1, 2]]

Get the items not repeated in a list

Take two lists, second with same items than first plus some more:
a = [1,2,3]
b = [1,2,3,4,5]
I want to get a third one, containing only the new items (the ones not repeated):
c = [4,5]
The solution I have right now is:
>>> c = []
>>> for i in ab:
... if ab.count(i) == 1:
... c.append(i)
>>> c
[4, 5]
Is there any other way more pythonic than this?
Thanx folks!
at the very least use a list comprehension:
[x for x in a + b if (a + b).count(x) == 1]
otherwise use the set class:
list(set(a).symmetric_difference(set(b)))
there is also a more compact form:
list(set(a) ^ set(b))
If the order is not important and you can ignore repetitions within a and b, I would simply use sets:
>>> set(b) - set(a)
set([4, 5])
Sets are iterable, so most of the times you do not need to explicitly convert them back to list. If you have to, this does it:
>>> list(set(b) - set(a))
[4, 5]
Items in b that aren't in a, if you need to preserve order or duplicates in b:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4, 4, 5]
>>> a_set = set(a)
>>> [x for x in b if x not in a_set]
[4, 4, 5]
Items in b that aren't in a, not preserving order, and not preserving duplicates in b:
>>> list(set(b) - set(a))
[4, 5]
I'd say go for the set variant, where
set(b) ^ set(a) (set.symmetric_difference())
only applies if you can be certain that a is always a subset of b, but in that case has the advantage of being commutative, ie. you don't have to worry about calculating set(b) ^ set(a) or set(a) ^ set(b); or
set(b) - set(a) (set.difference())
which matches your description more closely, allows a to have extra elements not in b which will not be in the result set, but you have to mind the order (set(a) - set(b) will give you a different result).
Here are some different possibilities with the sets
>>> a = [1, 2, 3, 4, 5, 1, 2]
>>> b = [1, 2, 5, 6]
>>> print list(set(a)^set(b))
[3, 4, 6]
>>> print list(set(a)-set(b))
[3, 4]
>>> print list(set(b)-set(a))
[6]
>>> print list(set(a)-set(b))+list(set(b)-set(a))
[3, 4, 6]
>>>
Another solution using only lists:
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]
c = [n for n in a + b if n not in a or n not in b]
a = [1, 2 ,3]
b = [1, 2, 3, 4, 5]
c=[]
for x in a:
if x not in b:
c.append(x)
print(c)

Categories

Resources