我想读取一个文件并通过split()方法从其中一个列创建一个列表,并将此列表传递给另一个方法。有人可以解释什么是实现这一目标的最pythonic方法吗?
def t(fname):
k = []
with open(fname, 'rU') as tx:
for line in tx:
lin = line.split()
k.append(lin[1])
res = anno(k)
for id in res.items():
if i > 0.05:
print(i)
我想传递' k'作为anno()方法的一个列表。但是通过这种方式,我有多个列表,但没有一个(必需)。
答案 0 :(得分:1)
而不是一个接一个地附加到该列表,为什么不为k = [(line.split())[1] for line in tx]
之类的特定语句设置循环。
而不是使用with open(file) as:
我使用tx = open(file)
所以只要你有它需要你可以使用它并使用tx.close()关闭它,它消除了那个额外的级别意图。
def t(fname):
k = []
tx = open(fname, 'rU')
k = [(line.split())[1] for line in tx]
tx.close()
res = anno(k)
for i in res.items():
if i > 0.05:print(i)
答案 1 :(得分:0)
当你想创建一个新列表时,lsit comprehensions会采用以下首选方式:
def t(fname):
with open(fname, 'rU') as tx:
k = [(line.split())[1] for line in tx]
res = anno(k)
for i in res.items():
if i > 0.05:
print(i)
答案 2 :(得分:0)
我认为你在嵌套时犯了一个错误。在for循环之外构建列表后,您必须致电anno()
。
def t(fname):
k = []
for line in open('fname'):
k.append(line.split()[1])
res = anno(k)