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

标签 python for-loop

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

文件1:

2  4  Apple
6  7  Samsung

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

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

输出结果应如下所示。

结果:

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

我对循环迭代及其断点感到困惑。

最佳答案

试试这个:

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")

关于python - 打印循环内位置之间的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059080/

相关文章:

c - 仅反转字符串中的某些单词

c - 为什么我得到垃圾字符?

c - 存储用户的数组值并在存储数组的位置打印它(仅使用数组和 for 循环)

python - 逗号在作业中有什么用?

python - Pytest 跳过测试说 "asyncio not installed"

python - 无法打开数据库文件

python - 如何使用 tkFileDialog 获取文件的绝对路径?

python - 将列表对象缩短为仅数字并在 Python 中创建新列表

python - 检测异常是否已经在 Python 2.7 的嵌套 with 语句中处理

java - 当用户每次点击加号按钮时,如何添加+30?