如何单独打印列表而不是合并它们?

时间:2015-04-17 13:33:36

标签: python list loops

datadicabst是列表,数据形式为:[[0, 1, 0, 0 , 1...0],[1, 0, 0, 1, 0, 1....0]],循环之后,我得到的结果如下:

abst = ['PS50802', 'PS50803', 'PS50804', 'PS50805', 'PS50806', 'PS50807', 'PS50808', 'PS50809', 'PS50810', 'PS50811', 'PS50812', 'PS50813', 'PS50814',......]

dic = ['PS50102' 'PS50101' 'PS50106' 'PS50199' 'PS50196' 'PS00832' 'PS50072'...]

  

[0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]

看起来两个单独的列表合并为一个列表,但我怎样才能得到如下结果:

  

[[0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0,0,0,0, 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0,0,0,0,0.0,1.0,0.0,0.0]]

lines = []

for x in range(0, 2):
    for item in dic:
        for i,j in enumerate(abst):       
            if item == j:
                lines.append(data[x][i])

print lines

1 个答案:

答案 0 :(得分:1)

如果您想保留两个列表的列表,可以尝试:

lines = []
for x in range(0, 2):
    line = []
    for item in dic:
        for i,j in enumerate(abst):       
            if item == j:
                line.append(data[x][i])
    lines.append(line)

print lines

您可以简化

lines = []
for x in range(0, 2):
    line = []
    for item in dic:
        if item in abst:
            i = abst.index(item)
            line.append(data[x][i])
    lines.append(line)

lines = []
for x in range(0, 2):
    line = [data[x][abst.index(item)] for item in dic if item in abst]
    lines.append(line)

最后,有一个列表理解:

lines = [ [data[x][abst.index(item)] for item in dic if item in abst] for x in range(0, 2) ]