Merge different lists together in Python

自闭症网瘾萝莉.ら 提交于 2021-02-11 12:58:06

问题


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).

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

Code:

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    

回答1:


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

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

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.




回答2:


Addition operator + is what you might want.

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    

Will output [1, 2, 3, 4, 5, 6]




回答3:


You might want to have a look at the following questions:

  • How to append list to second list (concatenate lists)
  • Combining lists into one
  • join list of lists in python

Basically, if you're reading your lines in a loop, you can do like

result = []
for line in file:
    newlist = some_function(line) # newlist contains the result list for the current line
    result = result + newlist



回答4:


You can just add them: [1] + [2] = [1, 2].



来源:https://stackoverflow.com/questions/13481703/merge-different-lists-together-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!