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    
2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That's the problem, I do not know how to join them to another list
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 += <item> or listoflists.extend(...) depending on what you're trying to do. This might help.
sir, what is "*" means ?
3

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

1 Comment

Thank you, it gives me screen full of lines but I try to it more suitable for me.
3

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]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.