如何访问2d列表中的元组

时间:2018-04-30 00:42:37

标签: python list tuples

我有一个像这样的二维名单:

VS Code

我想访问并使用每个元组的第一个元素(索引0)。

我怎么能在python中做到这一点?

2 个答案:

答案 0 :(得分:1)

我的问题不明确,但如果我理解正确,first就是2D列表中任何元组中第一项的列表。

arr = [[0, (1, 2), (2, 1), (3, 3)],
[(1, 4), (3, 'y'), ('x', 'y'), ('x', 'y')],
[(2, 1), (1, 'y'), ('x', 'y'), ('x', 'y')],
[(3, 1), ('x', 'y'), ('x', 'y'),('x', 'y')]]

firsts = []
for row in arr:
    for tup in row:
        if not isinstance(tup, tuple):
            continue
        firsts.append(tup[0])

答案 1 :(得分:1)

我也不清楚,但如果除了元组中的第一项之外你想要的元素不在元组中,你可以使用以下内容:

og = [[0, (1, 2), (2, 1), (3, 3)],
     [(1, 4), (3, 'y'), ('x', 'y'), ('x', 'y')],
     [(2, 1), (1, 'y'), ('x', 'y'), ('x', 'y')],
     [(3, 1), ('x', 'y'), ('x', 'y'),('x', 'y')]]
firsts = [x[0] if isinstance(x, tuple) else x for y in og for x in y]

如果您只是在寻找带有元组的项目,请将逻辑移动一下:

firsts = [x[0] for y in og for x in y if isinstance(x, tuple)]
相关问题