0

给定以下列表:

[[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], [0.02, 0.02, 0.015], [0.026, 0.026, 0.02, 0.02, 0.02, 0.015], [0.021, 0.02] 17, 0.021, 0.0 , [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], [0.053, 0.052, 0.051, 0.023, 0.022], [0.016, 0.016]]

我如何循环浏览列表并从每个子列表中提取 #1,从每个子列表中提取 #2,从每个子列表中提取 #3 并生成单独的列表。

例如,在这种情况下,#1 应包括 0.074、0.02、0.026、0.021、0.077、0.063 和 0.016。他们将在一个单独的独立列表中。

我使用了while循环,但它对我不起作用:

a=0
b=len(data['stock'])

while a<=b - 1:
    print data['stock'][a][0]
            a = a + 1
    print "\n"


while a<=b - 1:
    print data['stock'][a][1]
        a = a + 1
print "\n"

while a<=b - 1:
    print data['stock'][a][2]
        a = a + 1
print "\n"

while a<=b - 1:
    print data['stock'][a][3]
        a = a + 1
print "\n"

while a<=b - 1:
    print data['stock'][a][4]
        a = a + 1
print "\n"

while a<=b - 1:
    print data['stock'][a][5]
        a = a + 1
print "\n"

while a<=b - 1:
    print data['stock'][a][6]
        a = a + 1
print "\n"

有多少我解决了这个问题并根据上述逻辑创建了列表?

4

2 回答 2

2

你可以使用itemgetter

>>> from operator import itemgetter
>>> map(itemgetter(0), data)
[0.074, 0.02, 0.026, 0.021, 0.077, 0.053, 0.016]
>>> map(itemgetter(1), data)
[0.073, 0.02, 0.026, 0.021, 0.076, 0.052, 0.016]

您还可以使用列表推导(可能更具可读性):

>>> [l[0] for l in data]
[0.074, 0.02, 0.026, 0.021, 0.077, 0.053, 0.016]
于 2012-12-16T03:57:23.003 回答
1

转置列表的一种方法是使用zip

>>> data = [[1,2,3],[4,5,6]]
>>> zip(*data)
[(1, 4), (2, 5), (3, 6)]

要解决数据形状不一致的问题,您可以使用izip_longest

>>> data = [[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], [0.02, 0.02, 0.015], [0.026, 0.026, 0.02, 0.02, 0.02, 0.015], [0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], [0.053, 0.052, 0.051, 0.023, 0.022], [0.016, 0.016]]
>>> from itertools import izip_longest
>>> izip_longest(*data)
<itertools.izip_longest object at 0x101d77c00>
>>> list(izip_longest(*data))
[(0.074, 0.02, 0.026, 0.021, 0.077, 0.053, 0.016), (0.073, 0.02, 0.026, 0.021, 0.076, 0.052, 0.016), (0.072, 0.015, 0.02, 0.02, 0.074, 0.051, None), (0.03, None, 0.02, 0.017, 0.055, 0.023, None), (0.029, None, 0.02, None, 0.045, 0.022, None), (0.024, None, 0.015, None, 0.021, None, None), (0.021, None, None, None, None, None, None), (0.02, None, None, None, None, None, None)]

因此:

>>> columns = list(izip_longest(*data))
>>> columns[0]
(0.074, 0.02, 0.026, 0.021, 0.077, 0.053, 0.016)
>>> columns[1]
(0.073, 0.02, 0.026, 0.021, 0.076, 0.052, 0.016)
>>> columns[2]
(0.072, 0.015, 0.02, 0.02, 0.074, 0.051, None)

我不确定你想为“#3”做什么——你的最后一个子列表只有两个元素。 izip_longest有一个fillvalue选项可以用来指定要做什么,默认为None(这就是为什么最后一个条目columns[2]None)。

于 2012-12-16T04:05:50.000 回答