在循环内的位置之间打印数据

时间:2017-11-01 16:09:26

标签: python for-loop

我有一个文件。 File1有3列。数据以制表符分隔

File1中:

2  4  Apple
6  7  Samsung

假设我运行10次循环循环。如果迭代在File1的第1列和第2列之间具有值,则从File1打印相应的第3列,否则打印“0”。

列可能已排序,也可能未排序,但第二列始终大于第1列。两列中的值范围在行之间不重叠。

输出结果应如下所示。

结果:

0
Apple
Apple
Apple
0
Samsung
Samsung
0
0
0

我在python中的程序在这里:

chr5_1 = [[]]
for line in file:
  line = line.rstrip()
  line = line.split("\t")
  chr5_1.append([line[0],line[1],line[2]])
  # Here I store all position information in chr5_1 list in list
chr5_1.pop(0)
for i in range (1,10):
  for listo in chr5_1:            
      L1 = " ".join(str(x) for x in listo[:1])
      L2 = " ".join(str(x) for x in listo[1:2])
      L3 = " ".join(str(x) for x in listo[2:3])
      if int(L1) <= i and int(L2) >= i:
          print(L3)
          break
      else:
          print ("0")
          break

我对循环迭代感到困惑,并且它破坏了点。

3 个答案:

答案 0 :(得分:2)

试试这个:

chr5_1 = dict()
for line in file:
    line = line.rstrip()
    _from, _to, value = line.split("\t")
    for i in range(int(_from), int(_to) + 1):
        chr5_1[i] = value

for i in range (1, 10):
    print chr5_1.get(i, "0")

答案 1 :(得分:1)

我认为这是else的工作:

position_information = []
with open('file1', 'rb') as f:
    for line in f:
        position_information.append(line.strip().split('\t'))

for i in range(1, 11):
    for start, through, value in position_information:
        if i >= int(start) and i <= int(through):
            print value
            # No need to continue searching for something to print on this line
            break
    else:
        # We never found anything to print on this line, so print 0 instead
        print 0

这会给出您正在寻找的结果:

0
Apple
Apple
Apple
0
Samsung
Samsung
0
0
0

答案 2 :(得分:0)

设定:

import io
s = '''2  4  Apple
6  7  Samsung'''

# Python 2.x
f = io.BytesIO(s)
# Python 3.x
#f = io.StringIO(s)

如果文件的行未按第一个排序:

import csv, operator
reader = csv.reader(f, delimiter = ' ', skipinitialspace = True)
f = list(reader)
f.sort(key = operator.itemgetter(0))

阅读每一行;做一些数学计算以确定要打印的内容以及打印多少内容;印刷品;迭代

def print_stuff(thing, n):
    while n > 0:
        print(thing)
        n -= 1
limit = 10
prev_end = 1

for line in f:
    # if iterating over a file, separate the columns
    begin, end, text = line.strip().split()
    # if iterating over the sorted list of lines
    #begin, end, text = line

    begin, end = map(int, (begin, end))
    # don't exceed the limit
    begin = begin if begin < limit else limit
    # how many zeros?
    gap = begin - prev_end
    print_stuff('0', gap)
    if begin == limit:
        break
    # don't exceed the limit
    end = end if end < limit else limit
    # how many words?
    span = (end - begin) + 1
    print_stuff(text, span)
    if end == limit:
        break
    prev_end = end
# any more zeros?
gap = limit - prev_end
print_stuff('0', gap)