In Python if I have 2 lists say:
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d)
I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function
Thanks
You can use a set intersection for that :)
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
If you only have unique elements, you can use the set data type and use intersection:
s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
Using sets:
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
def list_count_common(list_a, list_b):
result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
return result
print list_count_common(l1, l2) ## prints 2
Related
I have a list:
li = ['a','b','c','d']
I want to iterate and combine iteratively the elements in the list such as the first one is combined to the 2nd one and go on.
The final output I want is:
['a'],['a','b'],['a','b','c'],['a','b','c','d']
I tried using this way:
for i in range(0, len(li),i):
output = li[:i+i]
print(output)
But I am getting only this result:
[]
['a', 'b', 'c', 'd']
Any idea where I am wrong and how to do this properly?
You could modify the start and stop arguments in your use of range:
li = ['a', 'b', 'c', 'd']
for i in range(1, len(li) + 1):
output = li[:i]
print(output)
Output:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
Your range values are incorrect, and i is undefined. This is a much simpler loop:
li = ['a','b','c','d']
for i in range(len(li)):
output = li[:i+1]
print(i, output)
Output:
0 ['a']
1 ['a', 'b']
2 ['a', 'b', 'c']
3 ['a', 'b', 'c', 'd']
I am trying to iterate over two lists A and B. Where the B is equal to A - A[i], where i = 1:
For E.g. listA = ['A', 'B', 'C', 'D'].
For first Item, 'A' in List A, I
want the List B to have ['B', 'C', 'D'] For second Item 'B' in List A,
I want the List B to have ['A', 'C', 'D']
What I have tried until now.
listA = ['A', 'B', 'C', 'D']
for term in listA:
listA.remove(term)
for item in listA:
print(listA)
If all you want is to print the sublists, it will be like:
for i in range(len(listA)):
print(listA[:i]+listA[i+1:])
Or,
for i in listA:
print(list(set(listA) - set(i)))
Try this,
>>> la = ['A', 'B', 'C', 'D']
>>> for i in la:
_temp = la.copy()
_temp.remove(i)
print(_temp)
Output:
['B', 'C', 'D']
['A', 'C', 'D']
['A', 'B', 'D']
['A', 'B', 'C']
*If you want to assign the print output to new variables, use a dictionary where the key will the name of list and value is printted output.
Is this what you want?
listA = ['A', 'B', 'C', 'D']
Bs = \
[listA[:idx] + listA[idx + 1:]
for idx
in range(len(listA))]
for B in Bs:
print(B)
Taking the above solutions a step further, you can store a reference to each of the resulting list in the corresponding variable using a dictionary comprehension:
keys_map = {x: [item for item in listA if item != x] for x in listA}
print(keys_map)
Output
{
'A': ['B', 'C', 'D'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D'],
'D': ['A', 'B', 'C']
}
and access the desired key like so
keys_map.get('A')
# returns
['B', 'C', 'D']
I was wodnering if there was any way to find the common elements of three lists, whilst ignoring a list that is empty among the three.
For example I know that:
a = ['a', 'b', 'c', 'd']
b = ['a', 'v', 'd', 'g']
v = ['d']
>>> set(a).intersection(b, v)
{'d'}
but I was wondering if there was a way to do this:
a = ['a', 'b', 'c', 'd']
b = ['a', 'v', 'd', 'g']
v = []
>>> comparison_method(a, b, v)
{'a', 'd'}
Or if 2 out of 3 lists were empty, it would just return the list that wasn't.
Using filter and then set intersection:
set.intersection(*map(set,filter(None, [a,[],[]])))
O/P: set(['a', 'c', 'b', 'd'])
set.intersection(*map(set,filter(None, [a,b,[]])))
O/P: set(['a', 'd'])
set.intersection(*map(set,filter(None, [a,b,v])))
O/P : set(['d'])
As jme suggested which is a more better solution
set.intersection(*(set(x) for x in [a, b, v] if x))
Just filter out all the list that have len (i.e. length is not zero) and use set-intersection-
>>>a = ['a', 'b', 'c', 'd']
>>>b = ['a', 'v', 'd', 'g']
>>>v=[]
>>>input_list = [a,v,b]
>>>result = reduce(set.intersection,map(set,filter(len,input_list)))
>>>set(['a', 'd'])
Sure, very similar to this, but just filter out the empty lists before running the intersection test:
def comparison_method(*args):
sets = [set(arg) for arg in args if arg]
if not sets:
return []
result = sets[0]
for s in sets[1:]:
result = result.intersection(s)
return result
a = ['a', 'b', 'c', 'd']
b = ['a', 'v', 'd', 'g']
v = []
>>> comparison_method(a, b, v)
{'a', 'd'}
There are two lists:
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
I want to find the same elements from these two lists, that is:
['a', 'c', 'e']
then I want to print out the element we found, for example, 'a' from both lists, that is: ['a', 'a', 'a'].
The result I want is as follows:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
I try to doing in this way:
c = []
for item_k in k:
for item_j in j:
if item_k== item_j:
c.append(item_k)
c.append(item_j)
However, the result is ['a', 'a', 'c', 'c', 'e', 'e']
Also in this way:
c=[]
for item_k in k:
if item_k in l:
c.append(item_k)
d=l.count(item_k)
c.append(item_k*d)
print c
But it do not works, can anybody tell me how to do it? really appreciate your help in advance
result = [x for x in sorted(k + l) if x in k and x in l]
print(result)
results:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
Since you want to pick up elements from both lists, the most straight forward way is probably to iterate over both while checking the other one (this is highly optimizatiable if you depend on speed for doing this):
merged = []
for el in list1:
if el in list2:
merged.append(el)
for el in list2:
if el in list1:
merged.append(el)
.. if the order of the elements is important, you'll have to define an iteration order (in what order do you look at what element from what array?).
If the lists are sorted and you want the result to be sorted:
sorted([x for x in list1 if x in set(list2)] + [x for x in list2 if x in set(list1)] )
You can use set operations to intersect and then loop through, appending to a new list any that match the intersected list
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
common_list = list(set(k).intersection(set(l)))
all_results = []
for item in k:
if item in common_list:
all_results.append(item)
for item in l:
if item in common_list:
all_results.append(item)
print sorted(all_results)
output:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
Here's a compact way. Readability might suffer a little, but what fun are comprehensions without a little deciphering?
import itertools
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
combined = [letter for letter in itertools.chain(k,l) if letter in l and letter in k]
Here is an implementation that matches your initial algorithm:
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l=['a', 'c', 'e']
c=[]
for x in l:
count = 0
for y in k:
if x == y:
count += 1
while count>=0:
c.append(x)
count = count -1
print c
I currently have this function, which I'd like to make scalable to take in more lists. In other words, I'd like to use this function whether I have to combine 2 lists or 10 lists.
l1 = [['a','b','c'],['d','e','f']]
l2 = [['A','B','C'],['D','E','F']]
[L1 + L2 for L1, L2 in zip(l1, l2)]
result should be:
[['a','b','c','A','B','C'],['d','e','f','D','E','F']]
Use:
[sum(l, []) for l in zip(*lists)]
Demo:
>>> l1 = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> l2 = [['A', 'B', 'C'], ['D', 'E', 'F']]
>>> lists = (l1, l2)
>>> [sum(l, []) for l in zip(*lists)]
[['a', 'b', 'c', 'A', 'B', 'C'], ['d', 'e', 'f', 'D', 'E', 'F']]
or, as a function:
def combine_lists(*lists):
return [sum(l, []) for l in zip(*lists)]
combine_lists(l1, l2)