2

How do I return my list so that the list is composed of strings rather than lists?

Here is my attempt:

def recipe(listofingredients):
    listofingredients = listofingredients 
    newlist = []
    newlist2 = []

    for i in listofingredients:
        listofingredients = i.strip("\n")
        newlist.append(listofingredients)

    for i in newlist:
        newlist = i.split()
        newlist2.append(newlist)
    return newlist2

result = recipe(['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n'])
print result

And my output is this:

[['12345'], ['eggs', '4'], ['$0.50'], ['flour', '5'], ['$2.00']]

Desired output:

['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']

I know that my issue here is appending one list to another, but I'm not sure how to use .strip() and .split() on anything other than a list.

kit-kat
  • 51
  • 7
  • theres a lot of wierd stuff going on in your code... but to answer your question, change `newlist2.append(newlist)` to `newlist2.extend(newlist)` – R Nar Dec 10 '15 at 00:39

2 Answers2

1

Use extend and split:

>>> L = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
>>> res = []
>>> for entry in L:
        res.extend(entry.split())
>>> res
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']

split splits at white spaces per default. Strings with a new line a the end and no space inside are turned into a one-element list:

>>>'12345\n'.split()
['12345']

Strings with a space inside split into a two-element list:

>>> 'eggs 4\n'.split()
['eggs', '4']

The method extend() helps to build a list from other lists:

>>> L = []
>>> L.extend([1, 2, 3])
>>> L
[1, 2, 3]
>>> L.extend([4, 5, 6])
L
[1, 2, 3, 4, 5, 6]
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
1

You can use Python's way of doing this. Take the advantage of list comprehension and strip() method.

recipes = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
recipes = [recipe.split() for recipe in recipes]
print sum(recipes, [])

Now the result will be

['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']

For further reading https://stackoverflow.com/a/716482/968442 https://stackoverflow.com/a/716489/968442

Community
  • 1
  • 1
nehem
  • 12,775
  • 6
  • 58
  • 84