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
189 views
in Technique[技术] by (71.8m points)

python - Finding in elements in a tuple and filtering them

Assuming I have a tuple like:

[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

[('img-1','iii'), ('img-2','jjj')]

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

One way:

>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> [t for t in l if t[0].startswith('img')]
[('img-1', 'iii'), ('img-2', 'jjj')]

Another way:

>>> filter(lambda x: x[0].startswith('img'), l)
[('img-1', 'iii'), ('img-2', 'jjj')]

The first is called a list comprehension. See F.C.'s answer for a related technique. The basic syntax is [{expression} for {item_var_or_vars} in {iterable} if {boolean_expression}]. It's semantically equivalent to something like this:

new_list = []
for {item_var_or_vars} in {iterable}:
    if {boolean_expression}:
        new_list.append({expression})

The if {boolean_expression} bit is optional, just as it is in the for loop.

The second is simply the built-in function filter, which accepts a test function and an iterable, and returns a list containing every element that "passes" the test function. lambda, if you haven't seen it before, is just a quick way of defining a function. You could do this instead:

def keep_this_element(element):
    return element[0].startswith('img')   # returns True for ('img...', '...')

new_list = filter(keep_this_element, l)   # keeps only elements that return True

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

...