简体   繁体   中英

Can you use the Filter() function on a list to create a new list from a larger list?

I would be using the list and filter functions to create a new list containing only the odd length stock tickers. I have used lambda before doing something similar with numbers but can't seem to translate it to words. My code is below..

list1 = ["GOOGL", "IBM", "AAPL", "FB", "M", "WMT"]

list(filter(lambda item: item[0] == "odd", list1))

I want the output to be all odd length stock tickers

['GOOGL','IBM', 'M', 'WMT']

With filter

print(list(filter(lambda x: len(x) % 2 == 1, list1)))

With list comprehension

print([i for i in list1 if len(i)%2==1])

Output:

['GOOGL', 'IBM', 'M', 'WMT']

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