python嵌套for循环不能超越第一 [英] python nested for-loop not executing beyond first
问题描述
为sor中的行:
NumsA,sourceA = line.split('####')
for line in sor:
if'####'in:
NumsB,sourceB = line.split('####')
if(NumsA == NumsB)& (sourceA!= sourceB):
print(Found reused Nums)
with open(reusedNums,'a')as reused:
reused.write(NumsA +''+ sourceA + ('setB:'+ NumsA +''+ sourceA)
print除了完成内部循环,外部循环的第一次迭代,
解决方案您正在尝试从同一文件读取两次。文件使用当前位置来确定接下来要读取的内容,并遍历内部循环中的其余行,将该位置移动到最后。
您可以通过回溯到文件的开头来修复:
sor.seek (0)
然而,循环遍历整个文件的每一行文件是真的低效。使用字典来跟踪上一行是否有相同的信息:
with open(sortedNums,r)作为sor,\
打开(reusedNums,'a')作为重用:
看过= {}
为sor中的行:
如果不是'####'in
继续
nums,source = line.rstrip()。split('####')
如果nums在看过和看过的[nums]!=源:
打印(找到重复使用的数量)
reused.write('{} {} {} \\\
'.format(nums,source,seen [nums]))
seen [nums] =来源
通过将数据存储在字典中,您只需要遍历文件 / em>。
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.
这篇关于python嵌套for循环不能超越第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!