0

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 i.e 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
4

2 に答える 2

2

純粋なリスト内包表記

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

上記はリスト内包表記です。ドキュメンテーション

于 2013-10-25T12:53:54.457 に答える
2
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.
于 2013-10-25T12:49:24.360 に答える