简体   繁体   中英

Python create list of 1 element if the element exist in another list

i have list:

var1 = "aaa"
var2 = "bbb"
var3 = "ccc"
var4 = "ddd"
l = [var1,var2,var3,var4]

now I like to find if string exists in this list so i do:

x = "bbb"
if x in l:

in this case, it exists, but now i like to create new list that contains only 1 element which is x is there any short way to create list that contains only x this do not work

if x in l:
   l = [x for X in l]

You can achieve this with a single list comprehension:

result = [element for element in mylist if element == x]

If you want to create a list of one element even it appears in the list multiple times, you can write the following:

l1 = ['aaa', 'bbb', 'ccc', 'ddd']
x = 'bbb'

l2 = [x] if x in l1 else []

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