使用 Python 从行列表中提取一列

Extract a column from a list of rows with Python

我有以下数据集,它是存储为嵌套列表的一系列行:

[['John', '35', 'UK'],
['Emma', '43', 'UK'],
['Lucy', '25', 'AU']]

(行总是相同的长度)

我需要 return 'UK', 'AU' 作为一个可迭代对象(与顺序无关)。

有没有一行return第三列中包含的唯一值,并且比这更简单?

set(list(map(list, zip(*l)))[2])

(参考:Transpose list of lists

>>> l = [['John', '35', 'UK'],
         ['Emma', '43', 'UK'],
         ['Lucy', '25', 'AU']]
>>> set(element[-1] for element in l)
('AU', 'UK')

你可以使用 numpy:

import numpy as np

arr = np.array([['John', '35', 'UK'],
                ['Emma', '43', 'UK'],
               ['Lucy', '25', 'AU']])

unique = np.unique(arr[:,2])

更改您自己的代码:

Python 3.x:

set(list(zip(*l)[2]))

Python 2.x:

set(zip(*l)[2])

演示:

l=[['John', '35', 'UK'],['Emma', '43', 'UK'],['Lucy', '25', 'AU']]
set(list(zip(*l)[2]))
{'AU', 'UK'}

您可以使用 list comprehension:

>>> L = [['John', '35', 'UK'],
['Emma', '43', 'UK'],
['Lucy', '25', 'AU']]
>>> set([i[2] for i in L])
set(['AU', 'UK'])

我觉得实际bsuire的需求比较复杂,所以我推荐使用pandas来处理这样的需求,更加强大和灵活。

所以,在这种情况下如何使用pandas:

In [17]: import pandas as pd

In [18]: a = [['John', '35', 'UK'],
   ....: ['Emma', '43', 'UK'],
   ....: ['Lucy', '25', 'AU']]

In [19]: b = pd.DataFrame(a)

In [20]: b
Out[20]:
      0   1   2
0  John  35  UK
1  Emma  43  UK
2  Lucy  25  AU

In [21]: b[2].unique()
Out[21]: array(['UK', 'AU'], dtype=object)

In [22]: