Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

python - Filter list's elements by type of each element

I have list with different types of data (string, int, etc.). I need to create a new list with, for example, only int elements, and another list with only string elements. How to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can accomplish this with list comprehension:

integers = [elm for elm in data if isinstance(elm, int)]

Where data is the data. What the above does is create a new list, populate it with elements of data (elm) that meet the condition after the if, which is checking if element is instance of an int. You can also use filter:

integers = list(filter(lambda elm: isinstance(elm, int), data))

The above will filter out elements based on the passed lambda, which filters out all non-integers. You can then apply it to the strings too, using isinstance(elm, str) to check if instance of string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...