简体   繁体   English

如何在Python中索引嵌套列表?

[英]How to index nested lists in Python?

I have a nested list as shown below: 我有一个嵌套列表,如下所示:

A = [('a', 'b', 'c'),
     ('d', 'e', 'f'),
     ('g', 'h', 'i')]

and I am trying to print the first element of each list using the code: 我试图使用代码打印每个列表的第一个元素:

A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
print A[:][0]

But I get the following output: 但我得到以下输出:

('a', 'b', 'c')

Required output: 所需输出:

('a', 'd', 'g')

How to get this output in Python? 如何在Python中获得此输出?

A[:] just creates a copy of the whole list, after which you get element 0 of that copy. A[:]只创建整个列表的副本,之后您将获得该副本的元素0

You need to use a list comprehension here: 你需要在这里使用列表理解:

[tup[0] for tup in A]

to get a list, or use tuple() with a generator expression to get a tuple: 获取列表,或使用带有生成器表达式的tuple()来获取元组:

tuple(tup[0] for tup in A)

Demo: 演示:

>>> A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> [tup[0] for tup in A]
['a', 'd', 'g']
>>> tuple(tup[0] for tup in A)
('a', 'd', 'g')

You can transpose a list of lists/tuples with zip(*list_of_lists) then select the items you want. 您可以使用zip(*list_of_lists)转置列表/元组列表,然后选择所需的项目。

>>> a
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> b = zip(*a)
>>> b
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> b[0]
('a', 'd', 'g')
>>> 
>>> c = zip(*a)[0]
>>> c
('a', 'd', 'g')
>>>

Python lists don't work very well as multi-dimensional arrays. Python列表不能很好地用作多维数组。 If you're willing to add an extra dependency(eg if you're going to do a lot of array manipulation), numpy allows you to use the almost the exact syntax you're looking for 如果你愿意添加一个额外的依赖项(例如,如果你要进行大量的数组操作), numpy允许你使用你正在寻找的几乎所有语法

import numpy as np
A = np.array([('a', 'b', 'c'),
              ('d', 'e', 'f'),
              ('g', 'h', 'i')])

This outputs the row as an np.array(which can be accessed like a list): 这会将行输出为np.array(可以像列表一样访问):

>>> A[:,0]
array(['a', 'd', 'g'])

To get the first row as a tuple: 要将第一行作为元组:

>>> tuple(A[:,0])
('a', 'd', 'g')

You can also do it this way: 你也可以这样做:

>>> A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> map(lambda t:t[0], A)
['a', 'd', 'g']
>>> tuple(map(lambda t:t[0],A))
('a', 'd', 'g')

You can also get the behavior you want using pandas as follows: 您还可以使用pandas获取所需的行为,如下所示:

In [1]: import pandas as pd

In [2]: A = [('a', 'b', 'c'),
     ('d', 'e', 'f'),
     ('g', 'h', 'i')]

In [3]: df = pd.DataFrame(A)

In [4]: df[:][0]
Out[4]:
0    a
1    d
2    g
Name: 0, dtype: object

In [5]: df[:][0].values
Out[5]: array(['a', 'd', 'g'], dtype=object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM