0

我在 Python 中被称为新手。我对列表有困难。我有一个循环,它从文本文件中获取一些信息并通过函数。如果文本文件长度为 10 行,则输出将是 10 个单独的列表,例如:[0.45] [0.87] ... 等等,持续 n+1 次(取决于文本文件的长度)。

如何将它们放入单个列表中,例如 [0.45, 0.87, ...]?我尝试了不同的循环,但没有:(

我以前很感激:) .. 并为我糟糕的英语感到抱歉

代码:

from pyfann import libfann
import os
path="."
ext = ".net"
files = [file for file in os.listdir(path) if file.lower().endswith(ext)]
for j in files:
 ann = libfann.neural_net()
 ann.create_from_file(j)
 print j
 f=open('nsltest1.dat','r')
 for i in f:
  x=i.strip()
  y=[float(i) for i in x.split()]
  z=ann.run(y)
  print z    
4

4 回答 4

9

如果您将所有列表存储在列表中a

# a = [[.45], [.87], ...]
import itertools
output = list(itertools.chain(*a))

使这个答案比其他答案更好的原因在于它将任意数量的列表整齐地连接在一行中,而不需要for循环或类似的东西。

于 2012-11-20T20:41:32.707 回答
4

加法运算符+是您可能想要的。

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list) #replace ( and ) with spaces if you're using python 2.x    

将输出[1, 2, 3, 4, 5, 6]

于 2012-11-20T20:40:48.130 回答
4

您可能想看看以下问题:

基本上,如果你在循环中阅读你的行,你可以这样做

result = []
for line in file:
    newlist = some_function(line) # newlist contains the result list for the current line
    result = result + newlist
于 2012-11-20T20:44:07.630 回答
2

您可以添加它们:[1] + [2] = [1, 2].

于 2012-11-20T20:40:45.123 回答