开发者

Using Python version 2.6.4 how to program excels filter function

开发者 https://www.devze.com 2023-01-07 08:07 出处:网络
Thanks in advance. Using Excel in the data tab there is a filter option. I wish to implement that into a program I have been working on. It may be as simple as 1 line. If you know anythi开发者_如何转开

Thanks in advance. Using Excel in the data tab there is a filter option. I wish to implement that into a program I have been working on. It may be as simple as 1 line. If you know anythi开发者_如何转开发ng or if it is not possible in this version/programming language please let me know

Thanks!

For more information: I want to use the sort option to apply the filter so that when the excel document I create is opened the user does not have to highlight everything, then click Data tab and select filter. The source data doesnt make a difference.


There is a filter function in Python, however I am not too familiar with filter in Excel. Perhaps it is the same type of thing.

You can filter out items from a list based on if they satisfy a certain criteria. For example:

def want(s):
    return s in ('dog', 'cat', 'fish') # return true if the string is dog, cat or fish

filter(want, ['dog', 'dog', 'zebra', 'zebrafish', 'fish', 'foo'])
# Returns:  ['dog', 'dog', 'fish']

filter takes in a function that returns True or False as the first parameter. Then, it passes in each element in the list for the second parameter. If want('dog') returns True, it will return it in the resulting set. If it is False, it will not.


List comprehension (or generator expression).

data = ['dog', 'god', 'zebra', 'zebrafish', 'fish', 'foo']

result = [w for w in data if w.startswith('z')]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号