Python: Cannot import name/IndexError: List index out of range
Python: Cannot import name/IndexError: List index out of range
我对 Python 还是很陌生,大部分代码都不是我写的,我只是想让它工作。我有以下两个 .py 文件:
这个叫做FnSim.py-
import numpy,sys, os
import math
def intFn(kVars,params): # Do not change the name of this function
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
return I
else:
print 'Hello'
return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
This is the function that will do the actual simulating. Fill out the filepaths below.
"""
nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved
iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.
iMax = iList.max()
print iMax
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)
from generalSim import generalSim
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()
这个叫做generalSim.py-
import numpy
import os, sys
import fileinput
from FnSim import intFn
from random import random
class generalSim (object):
def __init__(self,KVDir):
self.KVDir = KVDir
def calcIList(self,params):
n = 0
iList = numpy.zeros(shape = (1))
for line in fileinput.input([self.KVDir]):
iList.resize(n+1)
kvAs = line.split(",")
kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
iList[n] = intFn(kvAx,params)
sys.stdout.write(str(n)+"\r")
sys.stdout.flush()
n+=1
return iList
def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):
nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
numpy.save(nTrueDir,nTrueList)
wList=iList[:]/iMax
wnList=numpy.zeros(shape=(wList.shape[0]))
for wn in range(len(wList)):
if wList[wn]>random():
wnList[wn] = 1
numpy.save(outputWeightDir,wnList)
我在标有 'data' 的文件夹中还有一个名为 FlatY.txt 的文本文件。 FlatY.txt 包含一百万行 Y 值。
我需要 运行 文件,以便我可以创建 FnSim.py 中列出的 .npy 文件。我不太了解 Linux,但我的意图是将文件放在 'data' 文件夹中。但是,如果我尝试编译 FnSim.py,控制台会显示:
Traceback (most recent call last):
File "FnSim.py", line 38, in <module>
from generalSim import generalSim
File "/home/gendreau/workspace/generalSim.py", line 5, in <module>
from FnSim import intFn
File "/home/gendreau/workspace/FnSim.py", line 38, in <module>
from generalSim import generalSim
ImportError: cannot import name generalSim
当我尝试 运行 generalSim.py 时,我得到了这个:
Traceback (most recent call last):
File "generalSim.py", line 5, in <module>
from FnSim import intFn
File "/home/gendreau/workspace/FnSim.py", line 41, in <module>
if sys.argv[1] == "i":
IndexError: list index out of range
如何解决这些问题并生成必要的文件?
这是一种解决方法,但请参阅下文,希望它对您的工作有所帮助:
因为你有很多循环导入,即第一个模块调用第二个模块,第二个模块调用第一个模块,依此类推,获得所需结果的最直接解决方案是合并两个文件,避免循环导入:
import numpy
import os, sys
import math
import fileinput
from random import random
class generalSim (object):
def __init__(self,KVDir):
self.KVDir = KVDir
def calcIList(self,params):
n = 0
iList = numpy.zeros(shape = (1))
for line in fileinput.input([self.KVDir]):
iList.resize(n+1)
kvAs = line.split(",")
kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
iList[n] = intFn(kvAx,params)
sys.stdout.write(str(n)+"\r")
sys.stdout.flush()
n+=1
return iList
def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):
nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
numpy.save(nTrueDir,nTrueList)
wList=iList[:]/iMax
wnList=numpy.zeros(shape=(wList.shape[0]))
for wn in range(len(wList)):
if wList[wn]>random():
wnList[wn] = 1
numpy.save(outputWeightDir,wnList)
def intFn(kVars,params): # Do not change the name of this function
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
return I
else:
print 'Hello'
return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
This is the function that will do the actual simulating. Fill out the filepaths below.
"""
nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved
iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.
iMax = iList.max()
print iMax
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()
此外,您必须 运行 这个文件,并在命令行中将参数 i
或 s
传递给它,或者直接从脚本中删除可忽略的行:
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()
或者你可以改变你的代码如下添加一个额外的变量作为 runmode
你可以通过这个设置实际的 运行ning 模式。
import numpy
import os, sys
import math
import fileinput
from random import random
######
run_mode = "s" # or you can change it to "i"
######
class generalSim (object):
def __init__(self,KVDir):
self.KVDir = KVDir
def calcIList(self,params):
n = 0
iList = numpy.zeros(shape = (1))
for line in fileinput.input([self.KVDir]):
iList.resize(n+1)
kvAs = line.split(",")
kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
iList[n] = intFn(kvAx,params)
sys.stdout.write(str(n)+"\r")
sys.stdout.flush()
n+=1
return iList
def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):
nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
numpy.save(nTrueDir,nTrueList)
wList=iList[:]/iMax
wnList=numpy.zeros(shape=(wList.shape[0]))
for wn in range(len(wList)):
if wList[wn]>random():
wnList[wn] = 1
numpy.save(outputWeightDir,wnList)
def intFn(kVars,params): # Do not change the name of this function
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
return I
else:
print 'Hello'
return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
This is the function that will do the actual simulating. Fill out the filepaths below.
"""
nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved
iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.
iMax = iList.max()
print iMax
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
####
if run_mode == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif run_mode == "s":
simFn()
####
我对 Python 还是很陌生,大部分代码都不是我写的,我只是想让它工作。我有以下两个 .py 文件:
这个叫做FnSim.py-
import numpy,sys, os
import math
def intFn(kVars,params): # Do not change the name of this function
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
return I
else:
print 'Hello'
return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
This is the function that will do the actual simulating. Fill out the filepaths below.
"""
nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved
iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.
iMax = iList.max()
print iMax
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)
from generalSim import generalSim
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()
这个叫做generalSim.py-
import numpy
import os, sys
import fileinput
from FnSim import intFn
from random import random
class generalSim (object):
def __init__(self,KVDir):
self.KVDir = KVDir
def calcIList(self,params):
n = 0
iList = numpy.zeros(shape = (1))
for line in fileinput.input([self.KVDir]):
iList.resize(n+1)
kvAs = line.split(",")
kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
iList[n] = intFn(kvAx,params)
sys.stdout.write(str(n)+"\r")
sys.stdout.flush()
n+=1
return iList
def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):
nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
numpy.save(nTrueDir,nTrueList)
wList=iList[:]/iMax
wnList=numpy.zeros(shape=(wList.shape[0]))
for wn in range(len(wList)):
if wList[wn]>random():
wnList[wn] = 1
numpy.save(outputWeightDir,wnList)
我在标有 'data' 的文件夹中还有一个名为 FlatY.txt 的文本文件。 FlatY.txt 包含一百万行 Y 值。
我需要 运行 文件,以便我可以创建 FnSim.py 中列出的 .npy 文件。我不太了解 Linux,但我的意图是将文件放在 'data' 文件夹中。但是,如果我尝试编译 FnSim.py,控制台会显示:
Traceback (most recent call last):
File "FnSim.py", line 38, in <module>
from generalSim import generalSim
File "/home/gendreau/workspace/generalSim.py", line 5, in <module>
from FnSim import intFn
File "/home/gendreau/workspace/FnSim.py", line 38, in <module>
from generalSim import generalSim
ImportError: cannot import name generalSim
当我尝试 运行 generalSim.py 时,我得到了这个:
Traceback (most recent call last):
File "generalSim.py", line 5, in <module>
from FnSim import intFn
File "/home/gendreau/workspace/FnSim.py", line 41, in <module>
if sys.argv[1] == "i":
IndexError: list index out of range
如何解决这些问题并生成必要的文件?
这是一种解决方法,但请参阅下文,希望它对您的工作有所帮助:
因为你有很多循环导入,即第一个模块调用第二个模块,第二个模块调用第一个模块,依此类推,获得所需结果的最直接解决方案是合并两个文件,避免循环导入:
import numpy
import os, sys
import math
import fileinput
from random import random
class generalSim (object):
def __init__(self,KVDir):
self.KVDir = KVDir
def calcIList(self,params):
n = 0
iList = numpy.zeros(shape = (1))
for line in fileinput.input([self.KVDir]):
iList.resize(n+1)
kvAs = line.split(",")
kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
iList[n] = intFn(kvAx,params)
sys.stdout.write(str(n)+"\r")
sys.stdout.flush()
n+=1
return iList
def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):
nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
numpy.save(nTrueDir,nTrueList)
wList=iList[:]/iMax
wnList=numpy.zeros(shape=(wList.shape[0]))
for wn in range(len(wList)):
if wList[wn]>random():
wnList[wn] = 1
numpy.save(outputWeightDir,wnList)
def intFn(kVars,params): # Do not change the name of this function
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
return I
else:
print 'Hello'
return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
This is the function that will do the actual simulating. Fill out the filepaths below.
"""
nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved
iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.
iMax = iList.max()
print iMax
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()
此外,您必须 运行 这个文件,并在命令行中将参数 i
或 s
传递给它,或者直接从脚本中删除可忽略的行:
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()
或者你可以改变你的代码如下添加一个额外的变量作为 runmode
你可以通过这个设置实际的 运行ning 模式。
import numpy
import os, sys
import math
import fileinput
from random import random
######
run_mode = "s" # or you can change it to "i"
######
class generalSim (object):
def __init__(self,KVDir):
self.KVDir = KVDir
def calcIList(self,params):
n = 0
iList = numpy.zeros(shape = (1))
for line in fileinput.input([self.KVDir]):
iList.resize(n+1)
kvAs = line.split(",")
kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
iList[n] = intFn(kvAx,params)
sys.stdout.write(str(n)+"\r")
sys.stdout.flush()
n+=1
return iList
def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):
nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
numpy.save(nTrueDir,nTrueList)
wList=iList[:]/iMax
wnList=numpy.zeros(shape=(wList.shape[0]))
for wn in range(len(wList)):
if wList[wn]>random():
wnList[wn] = 1
numpy.save(outputWeightDir,wnList)
def intFn(kVars,params): # Do not change the name of this function
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
return I
else:
print 'Hello'
return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
This is the function that will do the actual simulating. Fill out the filepaths below.
"""
nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved
iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.
iMax = iList.max()
print iMax
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
####
if run_mode == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif run_mode == "s":
simFn()
####