2014-10-09 73 views
-2

我已经给出了每个这些元组中存储的12个元素的全部数据(确切地说900个元组)。元组 - Python 2.7

我需要加载元组中的第二个元素。

我将如何从900个元组中的每一个中提取第二个元素?任何帮助或建议如何做到这一点将不胜感激。

+0

在这里你去,请阅读本:http://www.tutorialspoint.com/python/python_tuples.htm – DBedrenko 2014-10-09 08:06:06

回答

0

这是你想要的吗?告诉我它是否有效。

... 
yourTuples = [(....), (.....)] 
result = [] 
for item in yourTuples: 
    result.append(item[1]) 

print result 
+0

谢谢,是的,这就是我试图做的似乎工作:) – newprogrammer1001 2014-10-09 08:12:51

+0

列表理解可能会更有效率 - 看到使用zip,地图,列表解析和显式for循环之间的时间差异将是有趣的。 – 2014-10-09 11:01:07

+0

@ newprogrammer1001如果有效,请不要忘记接受它作为答案。:) – 2014-10-09 12:19:51

5
t1 = (something here) 
t2 = (something here) 
. 
. 
. 
t900= (something here) 
l = [t1, t2 ,... ,t900] 
a = [i[1] for i in l] 
print a 
+0

@ newprogrammer1001检查解决方案。 – 2014-12-02 08:17:21

0

地图上名单:

list_of_tuples = [(..., ...), (..., ...), ...] 
second_elements = map(lambda x: x[1], list_of_tuples) 
0

您可以轻松地用Python包numpy

请参见下面的示例代码,

import numpy 

initial_list = [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), ] 

array = numpy.array(initial_list) 
print array[:,1] 
+0

这假设NumPy可以找到适合所有元组元素的单个'dtype'。 – 2014-10-09 08:29:30

0

如果你有一堆数据我ñ列表形式,你可以简单地做到这一点使用zip

lt=[(1,2,3),(4,5,6),(7,8,9)] 
print zip(*lt)[1] 

输出:

(2, 5, 8)