在Python中合并不同的列表 [英] Merge different lists together in Python

查看:60
本文介绍了在Python中合并不同的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中被称为新手.我在清单上有困难.我有一个循环,该循环从文本文件中获取一些信息并通过函数.如果文本文件长度为10行,则输出将为10个单独的列表,如下所示:[0.45][0.87]...依此类推,持续n + 1次(取决于文本文件的长度).

I am so called newbie in Python. I have difficulties with lists. I have a loop which take some info from textfile and goes through function. If textfiles lenght is 10 rows then output will be 10 separate lists, like that: [0.45] [0.87] ... and so on, for n+1 times(it depends how long textfile is).

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

How can I put them into single list, like [0.45, 0.87, ...]? I experimented with different loops but nothing :(

我以前非常感谢:)..并对我的英语不好说

I am previously thankfull :) .. and sry about my bad english

代码:

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    

推荐答案

如果所有列表都存储在列表 a 中,

If you have all of your lists stored in a list a,

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

此答案之所以比其他答案更好,是因为它整齐地将任意数量的列表连接在一起,而不需要 for 循环之类的东西.

What makes this answer better than the others is that it neatly joins an arbitrary number of lists together in one line, without a need for a for loop or anything like that.

这篇关于在Python中合并不同的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆