1

I need to convert a series of lists into one single line of text separated by a blank space

def Function(lists):
    Numbers= str(len(lists))+ " "
    for item in lists:
        for items in item:
            Numbers = Numbers + str(items) +'  ' 
    print Numbers

Data = [[1,2,3],[10,20,30]]
Function(Data)

this should return "2 1 2 3 10 20 30" However this approach is very slow.

is there a way to do this faster?

user2339945
  • 623
  • 1
  • 9
  • 14

3 Answers3

4

You are creating a new string on every + operator, which is horribly slow(when applied a lot). Instead use a generator expression with str.join:

In [11]: from itertools import chain

In [12]: data = [[1,2,3],[10,20,30]]

In [13]: " ".join(str(i) for i in chain(*data))
Out[13]: '1 2 3 10 20 30'

Edit:

And you can append the list length with and method you want, since it doesn't affect performance much:

" ".join((str(len(data)), " ".join(str(i) for i in chain(*data)))

Edit2:

hcwhsa pointed out that generator expression has no advantage with str.join. So you may want to use a list comprehension instead of generator expression.

Community
  • 1
  • 1
utdemir
  • 26,532
  • 10
  • 62
  • 81
2

This was the simplest to me:

>>> data = [[1,2,3],[10,20,30]]
>>> " ".join([str(item) for var in data for item in var])
'1 2 3 10 20 30'

So you can write your function like so:

def fun(data):
    return " ".join([str(item) for var in data for item in var])

I do not know if this was a mistake on your behalf, but if you want to add the length of the list as the first number, then you can do the following:

def fun(data):
    return str(len(data)) + ' ' + " ".join([str(item) for var in data for item in var])
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
1

please consider to use join method of string

def Function(lists):
    data = " ".join(j for i in lists for j in i))
    return " ".join([len(lists), data])
oleg
  • 4,082
  • 16
  • 16