Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何访问二维列表中的元组_Python_List_Tuples - Fatal编程技术网

Python 如何访问二维列表中的元组

Python 如何访问二维列表中的元组,python,list,tuples,Python,List,Tuples,我有这样一个2d列表: [[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] for y in og for x in y if isinstance(x, tuple)] 我只想访问

我有这样一个2d列表:

[[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] for y in og for x in y if isinstance(x, tuple)]
我只想访问和处理每个元组的第一个元素(索引0)


在python中如何做到这一点?

我不清楚您的问题,但如果我理解正确,
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])

我也不清楚,但如果您希望除了元组中的第一个项之外,还使用非元组中的项,则可以使用以下方法:

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]
如果您只查找具有元组的项,请按如下方式移动逻辑:

[[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] for y in og for x in y if isinstance(x, tuple)]

第一行中的第一个项不是元组。我知道,但我想访问元组的[0]@RafaelÁquila。您希望这些第一个元组项位于何处?在列表中?在另一个元组中?通过一些索引获取它们?