通过开始字符

时间:2018-02-10 18:42:25

标签: python list tuples

我有一个元组,门:

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

由于我之前的洗牌,拉链和弹出:[(1,'C'),(2,'G1'),(3,'G2')]门也可能是这样的:*** doors = [(1,'G1'),(2,'G2')] **** 或doors= [(1,'G2'),(3,'C')]

有没有办法可以通过索引到元组来“pythonize”,只选择字母“G”中的元素(或者不选择“C”),并且只获得成对的整数123

到目前为止,我使用示例元组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

然后获取匹配的数字,在这种情况下为3

但是我得到了这个错误(第23行正在创建need_to_select):

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

2 个答案:

答案 0 :(得分:3)

列表理解:

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

这会迭代doors列表的元组,并在第二个元素包含G时获取第一个元素(整数)。

同样,如果你想在第二个元素不包含C时获得第一个元素:

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

示例:

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]

答案 1 :(得分:0)

@heemayl's list comprehension解决方案有一个功能替代方案。我只会将它用于多个或更复杂的标准,因为否则列表推导更具可读性和效率。

下面的几个例子,结果以元组的形式给出。

-----------             -------------
| Persons |             | Employees |
-----------             -------------
| Id      |   1 to 0..1 | Id        |
-----------             -------------