简体   繁体   中英

Generating a new List from two Separate Lists with one Line of Code

I am trying an exercise that requires you to:

write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.

I was able to do this, but one of the extra challenges is to:

Write this in one line of Python

I came up with the following code:

list_1 = [1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 89]
list_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 3, 13]
newList = []

newList = [x for x in list_1 if x in list_2 if x not in newList] #attempting one line

print(newList)
newList = []

for x in list_1:
    if x in list_2 and x not in newList:
        newList.append(x)

print(newList)

I get the following results:

[1, 1, 2, 3, 3, 3, 3, 3, 3, 3]
[1, 2, 3]

My single-line list comprehension seems to fail, can someone point out why that is?

A basic approach would be to cast newList to set and then recast it to list

print(list(set(newList)))

Or by using set intersection without any loops

print(list(set(list_1).intersection(list_2)))

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