简体   繁体   中英

Selecting element in tuple by starting character

I have a tuple, doors:

    doors = [(2, 'C'), (3, 'G1')]

Due to previous shuffling, zipping, and popping of what I originally had: [(1,'C'),(2,'G1'),(3,'G2')] doors could also be something like: *** doors = [(1,'G1'),(2,'G2')] **** or doors= [(1,'G2'),(3,'C')] .

Is there a way I can 'pythonize' by indexing into a tuple to only select elements with the letter 'G' in it (or not to select 'C'), and obtain only the paired integers 1 , 2 , or 3 ?

Here's something I have so far that produces an error, and an example of what I would want to obtain, using the example tuple doors = [(2, 'C'), (3, 'G1')] :

    >>> first_letter = 'G'
    >>> print('Search by:',first_letter)
    Search by: G
    # I want to obtain 'G1' = need_to_select, this is for me to get 3 later
    >>> need_to_select = [door for door in doors if (door[0] in first_letter)]
    need_to_select = G1

Then obtain the matching number, so 3 in this case.

But I get this error (line 23 is creating need_to_select):

    Traceback (most recent call last): File "python", line 23, in <module>

List comprehension:

[i for i, j in doors if 'G' in j]

This iterates over the tuples of the doors list and gets the first element (the integer) when the second element contains G .

Similarly, if you want to get first element when the second does not contain C :

[i for i, j in doors if not 'C' in j]  

Example:

In [56]: doors = [(2, 'C'), (3, 'G1')]

In [57]: [i for i, j in doors if 'G' in j]
Out[57]: [3]

In [60]: [i for i, j in doors if not 'C' in j]
Out[60]: [3]

There is a functional alternative to @heemayl's list comprehension solution. I would only use this for multiple or more complex criteria, since otherwise list comprehensions are more readable and efficient.

A couple of examples below, where results are given as tuples.

doors = [(2, 'C'), (3, 'G1')]

def selector(x):
    return 'G' in x[1]

def selector_not(x):
    return not 'C' in x[1]

list(zip(*filter(selector, doors)))[0]      # (3,)

list(zip(*filter(selector_not, doors)))[0]  # (3,)

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