Write a function that takes two lists as parameters. Your function should check if an element is in both lists. After checking all elements, your function should print the following:
These items are in both lists: (elements that are in both lists) I got this one right
These items are not in both lists: (elements that are not in both lists) This is the one I need help with
For example, given
listOne = ["a", "b", "c", "d"]
and listTwo = ["c", "d", "e", "f"]
your function would print
These items are in both lists: c d These items are not in both lists: abef
use the following function header:
def checkItemsInList(listOne, listTwo):
Below is the code I ended up with, for the items in both lists I got that part right, but for the part that asks for items that are not in both lists, I get the wrong output of ['b', 'a']
, when I need ['a','b','e','f']
.
INPUT
def checkItemsInList(listOne, listTwo):
listOne = ["a", "b", "c", "d"]
listTwo = ["c", "d", "e", "f"]
# for the items in both lists
print(list(set(listOne) & set(listTwo)))
# for the items not in both lists
list(set(listOne) - set(listTwo))
OUTPUT
['d', 'c']
['b', 'a']
You can use function symmetric_difference
>>> set(listOne).symmetric_difference(listTwo)
{'b', 'f', 'e', 'a'}
You didn't check for items that exist in list_b but not in list_a (you checked only the opposite direction):
in_both = list(set(listOne) & set(listTwo))
# for the items not in both lists
not_in_both = list(set(listOne) - set(listTwo)) + list(set(listTwo) - set(listOne))
or
not_in_both = list(set(listOne+listTwo)-set(in_both))
Check this if it works
def checkItemsInList(listOne, listTwo):
res = []
for i in listOne:
if i in listTwo:
res.append(i)
print(res)
For remaining elements, you can use
list(set(listOne) ^ set(listTwo))
Or you could try this list comprehension approach:
listOne = ["a", "b", "c", "d"]
listTwo = ["c", "d", "e", "f"]
def checkItemsInList(firstl, secondl):
comm = [ x for x in firstl if x in secondl]
uniq = [ j for j in firstl+secondl if j not in comm]
print('Elements in both : ', comm)
print('Elements not in both: ', uniq)
checkItemsInList(listOne,listTwo)
Output:
Elements in both : ['c', 'd']
Elements not in both: ['a', 'b', 'e', 'f']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.