0

我正在尝试在 Python 中的列表中获取列表的第二项。

例子:

people = [['John Doe', u'', u'25.78', u''], ['John Doe', u'', u'13.39', u''], ['John Doe', u'', u'11.93', u'0.00'], ['John Doe', u'', u'14.97', u'0.00'], ['John Doe', u'', u'14.34', u''], ['John Doe', u'', u'21.08', u''], ['John Doe', u'', u'13.24', u''], ['John Doe', u'', u'13.11', u'0.00'], ['John Doe', u'', u'', u''], ['John Doe', u'', u'19.45', u'0.00'], ['John Doe', u'', u'17.56', u''], ['John Doe', u'', u'20.57', u''], ['John Doe', u'', u'28.50', u''], ['John Doe', u'', u'24.38', u'0.00'], ['John Doe', u'', u'31.13', u''], ['John Doe', u'', u'17.20', u''], ['John Doe', u'', u'18.52', u'0.00'], ['John Doe', u'', u'6.42', u'0.00'], ['John Doe', u'', u'17.31', u'']]

我想要做的是获取列表中每个列表的第三个元素。

我希望我的回报是:

['25.78','13.39','11.93','14.97','14.34']等等。

还有,加分。u列表中每个项目前面的 会影响什么吗?

4

5 回答 5

2
In [57]: people = [['John Doe', u'', u'25.78', u''], ['John Doe', u'', u'13.39', u''], ['John Doe', u'', u'11.93', u'0.00'], ['John Doe', u'', u'14.97', u'0.00'], ['John Doe', u'', u'14.34', u''], ['John Doe', u'', u'21.08', u''], ['John Doe', u'', u'13.24', u''], ['John Doe', u'', u'13.11', u'0.00'], ['John Doe', u'', u'', u''], ['John Doe', u'', u'19.45', u'0.00'], ['John Doe', u'', u'17.56', u''], ['John Doe', u'', u'20.57', u''], ['John Doe', u'', u'28.50', u''], ['John Doe', u'', u'24.38', u'0.00'], ['John Doe', u'', u'31.13', u''], ['John Doe', u'', u'17.20', u''], ['John Doe', u'', u'18.52', u'0.00'], ['John Doe', u'', u'6.42', u'0.00'], ['John Doe', u'', u'17.31', u'']]

In [58]: [p[2] for p in people]
Out[58]: 
[u'25.78',
 u'13.39',
 u'11.93',
 u'14.97',
 u'14.34',
 u'21.08',
 u'13.24',
 u'13.11',
 u'',
 u'19.45',
 u'17.56',
 u'20.57',
 u'28.50',
 u'24.38',
 u'31.13',
 u'17.20',
 u'18.52',
 u'6.42',
 u'17.31']

字符串前面的u基本上表示它们是 unicode 字符串。如果要将它们转换为常规的 ascii 字符串(假设它们只有 ascii 字符):

In [59]: [str(p[2]) for p in people]
Out[59]: 
['25.78',
 '13.39',
 '11.93',
 '14.97',
 '14.34',
 '21.08',
 '13.24',
 '13.11',
 '',
 '19.45',
 '17.56',
 '20.57',
 '28.50',
 '24.38',
 '31.13',
 '17.20',
 '18.52',
 '6.42',
 '17.31']
于 2012-12-04T01:41:24.607 回答
1

您可以使用简单的列表推导来获取第三个元素。

numbers = [i[2] for i in people]

u表示它是一个 unicode 字符串。假设它包含ascii字符(在这种情况下确实如此),str如果您不想要 unicode,则可以使用。

numbers = [str(i[2]) for i in people]
于 2012-12-04T01:41:53.130 回答
1
result = [each[2] for each in people]
print(result)
于 2012-12-04T01:41:58.917 回答
0

另外,只是为了好玩:

result = []
for x in range(len(people)):
    result.append(people[x][2])
于 2012-12-04T01:52:26.513 回答
0

这里是 numpy

people = numpy.array(people)
print people[:,2]
于 2012-12-04T01:46:07.603 回答