So to give a rough example without any code written for it yet, I'm curious on how I would be able to figure out what both lists have in common.
Example:
listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']
I'd like to be able to return:
['a', 'c']
How so?
Possibly with variable strings like:
john = 'I love yellow and green'
mary = 'I love yellow and red'
And return:
'I love yellow and'
We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .
Use set intersection for this:
list(set(listA) & set(listB))
gives:
['a', 'c']
Note that since we are dealing with sets this may not preserve order:
' '.join(list(set(john.split()) & set(mary.split())))
'I and love yellow'
using join()
to convert the resulting list into a string.
--
For your example/comment below, this will preserve order (inspired by comment from @DSM)
' '.join([j for j, m in zip(john.split(), mary.split()) if j==m])
'I love yellow and'
For a case where the list aren't the same length, with the result as specified in the comment below:
aa = ['a', 'b', 'c']
bb = ['c', 'b', 'd', 'a']
[a for a, b in zip(aa, bb) if a==b]
['b']
i think this is what u want ask me anything about it i will try to answer it
listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']
new1=[]
for a in listA:
if a in listB:
new1.append(a)
john = 'I love yellow and green'
mary = 'I love yellow and red'
j=john.split()
m=mary.split()
new2 = []
for a in j:
if a in m:
new2.append(a)
x = " ".join(new2)
print(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With