简体   繁体   English

您可以在列表上使用 Filter() 函数从更大的列表中创建一个新列表吗?

[英]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.我在用数字做类似的事情之前使用过lambda ,但似乎无法将其翻译成文字。 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 filterfilter

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

With list comprehension使用list comprehension

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

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用列表理解来读取 function 并创建一个新列表? - How to use a list comprehension to read from a function and create a new list? Python - 通过应用过滤器从列表中创建新列表 - Python - Create new list from a list by applying filter 使用列表推导或map()从现有列表创建更大的列表 - Create larger list from an existing list using a list comprehension or map() 你能调用/使用从 Python 列表返回的函数吗? - Can you call/use a function returned from a list in Python? 使用循环从更大的列表中保存新列表 - Saving a new list from a a larger list using a loop 从给定列表创建新列表,以便新列表可以标记给定列表中的连续重复 - Create a new list from a given list such that the new list can flag consecutive repetitions in the given list 我如何从现有列表中创建一个列表(新),其中列表(新)的项目将在 python 中列出 - How can i create a list (new) from an existing list where items of list(new) will be list in python 如何从较大的列表中创建具有最小和最大日期的列表列表? - How to create list of lists with min and max date from larger list? 如何使用 Python 从较大的列表中创建一个小的随机列表 - How to create a small random list from a larger list with Python 从较大列表python制作较小列表的功能 - Function to make a smaller list from a larger list python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM