简体   繁体   中英

List & Loops in python3

This is the objectif: Write a function to get 2 list L1 and L2 and build and return a third list L3 made of the elements that are in both list L1 and list L2 only ie exclude any value that is only in L1 or only L2.

The problem: I am stuck in the loop (that will only take the values that both alist and blist share).

my code:

alist=input("Enter words separated by space: " ).split(" ")
blist=input("Enter words separated by space: " ).split(" ")
clist=[" "]
for i in alist,blist:
    if alist(i)==blist(i):
        clist=alist(i)+blist(i)
        return clist
clist = []
for i in alist:
    if i in blist:
        clist.append(i)

print clist
  1. You can use in operator to check if one value is present in other list.

    For example:

     alist = ["a", "b", "c"] print "b" in alist # will print True print "d" in alist # will print False 
  2. You can use append method in list to add a new item.

Pure list comprehension

>>> alist = ["a", "b", "c"]
>>> blist = ["a", "d", "c"]
>>> [var for var in alist if var in blist]
['a', 'c']

The above is a list comprehension. Documentation .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM