来自文件的Python嵌套循环

标签 python bash nested-loops

我有以下代码:

inputActionFile = '../action.txt'
inputDaerahFile = '../daerah.txt'
inputStuffFile = '../stuff.txt'
inputTermsFile = '../terms.txt'

outputFile = 'hasil.out'

inputAction = open(inputActionFile, 'r')
inputDaerah = open(inputDaerahFile, 'r')
inputStuff = open(inputStuffFile, 'r')
inputTerms = open(inputTermsFile, 'r')

output = open(outputFile, 'w')

for actionLine in inputAction:
 for daerahLine in inputDaerah:
  for stuffLine in inputStuff:
   for termsLine in inputTerms:
    keyword = actionLine.strip() + ' ' + daerahLine.strip() + ' ' + stuffLine.strip() + ' ' + termsLine
    output.write(keyword)

inputAction.close()
inputDaerah.close()
inputStuff.close()
inputTerms.close()
output.close()

我预计结果会遍历所有这些文件并将它们一个接一个地嵌套到输出文件中。但是,它只是迭代第四个循环。我在 BaSH 中做了类似的事情,想看看如何在 Python 中完成。 BaSH代码如下:

#!/bin/sh
input1=$1
input2=$2
input3=$3
input4=$4
output=$5

echo "###START###" > $output
#old_IFS=$IFS
IFS='
'  # new field separator, EOL

for line1 in `cat $input1`;
do
 for line2 in `cat $input2`;
 do
  for line3 in `cat $input3`;
  do
   for line4 in `cat $input4`;
   do
    echo $line1 $line2 $line3 $line4 >> $output;
   done
  done
 done
done

unset IFS;
#IFS=$old_IFS

最佳答案

每个循环只会遍历文件一次。循环成功后

for termsLine in inputTerms:

一次,每次到达那里时,它都会跳过此循环,因为您已到达 inputTerms 文件的末尾。

您需要在每个循环中重新打开每个文件(或至少对它们进行 seek(0)),或者将文件读入内存中的列表。

所以,要么:

inputAction = open(inputActionFile, 'r').readlines()
inputDaerah = open(inputDaerahFile, 'r').readlines()
inputStuff = open(inputStuffFile, 'r').readlines()
inputTerms = open(inputTermsFile, 'r').readlines()

或者:

for actionLine in open(inputActionFile, 'r'):
 for daerahLine in open(inputDaerahFile, 'r'):
  for stuffLine in open(inputStuffFile, 'r'):
   for termsLine in open(inputTermsFile, 'r'):
       etc....

关于来自文件的Python嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4458465/

相关文章:

python - 使用 Itertools 实现具有内部中断的可变级别嵌套循环

java - 为什么嵌套 Java 循环执行得非常快

Javascript:for 循环 'for(i=0; i < 3 ; i++)' 在没有使用 continue、break 或 return 的情况下过早终止

python - 如何在numpy中跨多个轴连接多个数组

Python—— Pandas : How to apply aggfunc to data in currency format?

python - 使用 im2txt 为大型 jpeg 集添加字幕

linux - 如何分配目录?

bash - 为什么我不能将 stdout 从 netcat 传递到 awk?

linux - shell 脚本。我的脚本中的命令替换问题

python - 如何打破多个循环?