mutionu
mutionu

Reputation: 11

Merge different lists together in Python

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    

Upvotes: 1

Views: 12666

Answers (4)

user1632861
user1632861

Reputation:

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]

Upvotes: 3

MartinStettner
MartinStettner

Reputation: 29164

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

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

Upvotes: 3

alestanis
alestanis

Reputation: 21863

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

Upvotes: 1

jdotjdot
jdotjdot

Reputation: 17052

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.

Upvotes: 11

Related Questions