如何同时使用for循环读取特定的多行?

时间:2016-08-14 19:32:35

标签: python for-loop

内容位于文本文件的list[info]中:

1,1,1703,385,157,339,1,-1,-1,-1

1,3,1293,455,83,213,1,-1,-1,-1

1,4,259,449,101,261,1,-1,-1,-1

1,5,1253,529,55,127,1,-1,-1,-1

2,1,1699,383,159,341,1,-1,-1,-1

2,3,1293,455,83,213,1,-1,-1,-1

2,4,261,447,101,263,1,-1,-1,-1

2,5,1253,529,55,127,1,-1,-1,-1

3,1,1697,383,159,343,1,-1,-1,-1

3,3,1293,455,83,213,1,-1,-1,-1

3,4,263,447,101,263,1,-1,-1,-1

3,5,1255,529,55,127,1,-1,-1,-1

4,1,1695,383,159,343,1,-1,-1,-1

4,3,1293,455,83,213,1,-1,-1,-1

4,4,265,447,101,263,1,-1,-1,-1

4,5,1257,529,55,127,1,-1,-1,-1

.
.
.

它们就像这些

我要展示一些照片。所以我认为你不必关心image_list和文件。无论如何,我想读这些:

结论=如果info [0]为1,我想读取info [2],info [3],info [4] info [5],它们以info [0]为1开始的行开始。

换句话说,

如果info [0]为1,我想打印如下

1703,385,157,339

1293,455,83,213

259,449,101,261

1253,529,55,127 

同时

我的代码如下:

**marks = [int(info[0])]

      for i, images_files in zip(marks, image_list):

             for s in range(i, i):

                  print int(info[2]), int(info[3]), int(info[4]), int(info[5])**

请帮帮我:)。

1 个答案:

答案 0 :(得分:2)

您可以创建一个整数值字典,列出您要打印的四个值:

from collections import defaultdict

lines = [
    '1,1,1703,385,157,339,1,-1,-1,-1',
    '1,3,1293,455,83,213,1,-1,-1,-1',
    '1,4,259,449,101,261,1,-1,-1,-1',
    '1,5,1253,529,55,127,1,-1,-1,-1',
    '2,1,1699,383,159,341,1,-1,-1,-1',
    '2,3,1293,455,83,213,1,-1,-1,-1',
    '2,4,261,447,101,263,1,-1,-1,-1',
    '2,5,1253,529,55,127,1,-1,-1,-1',
    '3,1,1697,383,159,343,1,-1,-1,-1',
    '3,3,1293,455,83,213,1,-1,-1,-1',
    '3,4,263,447,101,263,1,-1,-1,-1',
    '3,5,1255,529,55,127,1,-1,-1,-1',
    '4,1,1695,383,159,343,1,-1,-1,-1',
    '4,3,1293,455,83,213,1,-1,-1,-1',
    '4,4,265,447,101,263,1,-1,-1,-1',
    '4,5,1257,529,55,127,1,-1,-1,-1',
]

line_map = defaultdict(list)
for line in lines:
    values = line.split(',')
    line_map[int(values[0])].append(','.join(values[2:6]))

print line_map[1]  # ['1703,385,157,339', '1293,455,83,213', '259,449,101,261', '