python with循环_python嵌套for循环不能超越第一

This script is meant to read through a file and take in the number (numA) and the text next to it (sourceA). It then uses this and compares it to every other line in the file. If a match in "nums" is found but not in sources, it writes the num to a file along with the sources it appears in.

with open(sortedNums, "r")as sor:

for line in sor:

NumsA, sourceA = line.split('####')

for line in sor:

if '####' in line:

NumsB, sourceB = line.split('####')

if (NumsA == NumsB) & (sourceA != sourceB):

print("Found reused Nums")

with open(reusedNums, 'a')as reused:

reused.write(NumsA + ' ' + sourceA + ' ' + sourceB)

print ("setA: " + NumsA + ' ' + sourceA)

print ("setB: " + NumsB + ' ' + sourceB)

Most of this is working except that it does the full inner loop but only the first iteration of the outer loop

解决方案

You are trying to read twice from the same file. Files use a current position to determine what to read next, and iterating over the remaining lines in the inner loop, you moved that position all the way to the end.

You could 'fix' that by seeking back to the start of the file with:

sor.seek(0)

However, looping over the whole file for every line in that file is really inefficient. Use a dictionary to track if you have seen the same information on a previous line:

with open(sortedNums, "r")as sor, \

open(reusedNums, 'a') as reused:

seen = {}

for line in sor:

if not '####' in line:

continue

nums, source = line.rstrip().split('####')

if nums in seen and seen[nums] != source:

print("Found reused Nums")

reused.write('{} {} {}\n'.format(nums, source, seen[nums]))

seen[nums] = source

By storing data in a dictionary, you only have to loop over the file once.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值