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

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    
Lesmana
  • 25,663
  • 9
  • 82
  • 87
mutionu
  • 11
  • 1
  • 1
  • 4
  • Copy/pastle your code here, then we might be able to help – theAlse Nov 20 '12 at 20:41
  • Possible duplicate of [How to append list to second list (concatenate lists)](http://stackoverflow.com/questions/1720421/how-to-append-list-to-second-list-concatenate-lists) – janot Apr 16 '16 at 11:03

4 Answers4

11

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.

jdotjdot
  • 16,134
  • 13
  • 66
  • 118
  • That's the problem, I do not know how to join them to another list – mutionu Nov 21 '12 at 17:10
  • Well, your code is a little convoluted to begin with, but what you could do is outside looping through the text you could instantiate a variable `listoflists = []` and then in the `for` loop add each list item to the list with `listoflists.append(...)` or `listoflists += ` or `listoflists.extend(...)` depending on what you're trying to do. [This](http://docs.python.org/2/tutorial/datastructures.html) might help. – jdotjdot Nov 23 '12 at 07:22
  • sir, what is "*" means ? – affhendrawan Feb 28 '18 at 06:04
4

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]

4

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
Community
  • 1
  • 1
MartinStettner
  • 28,719
  • 15
  • 79
  • 106
2

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
alestanis
  • 21,519
  • 4
  • 48
  • 67