2

I have a list of different things and I was wondering how to split it every time it hits a new name?

So what I would like to have is have it take a list that looks like this:

list = [corn, 14, 2, 500, broccoli, 2, 10, 1400, potato, 2, 14, 7]

and it will create 3 lists:

list1 = [corn, 14, 2, 500]

list2 = [broccoli, 2, 10, 1400]

list3 = [potato, 2, 14, 7]

I am guessing it would be something along the lines of a loop that repeats a new list until it hits a non integer, but I really dont know how it would look set up.

Celeo
  • 5,583
  • 8
  • 39
  • 41
Pewkie
  • 53
  • 1
  • 5
  • @zsong what about if `a_list = [corn, 14, 2, broccoli, potato, 2, 14, 7]`? – gboffi Oct 13 '14 at 23:17
  • @veedrac, the question is: "I have a list of different things and I was wondering how to split it every time it hits a new name?". – gboffi Oct 14 '14 at 17:04

5 Answers5

2

Try this, assuming that new names appear every four elements as in the sample input:

lst = ['corn', 14, 2, 500, 'broccoli', 2, 10, 1400, 'potato', 2, 14, 7]
[lst[i:i+4] for i in xrange(0, len(lst), 4)]
=> [['corn', 14, 2, 500], ['broccoli', 2, 10, 1400], ['potato', 2, 14, 7]]

The above will return a list of sublists, split every four elements. If you're certain that there will be exactly twelve elements in the input list, it's possible to directly assign the resulting sublists:

lst1, lst2, lst3 = [lst[i:i+4] for i in xrange(0, len(lst), 4)]

Now each variable will contain the expected result:

lst1
=> ['corn', 14, 2, 500]
lst2
=> ['broccoli', 2, 10, 1400]
lst3
=> ['potato', 2, 14, 7]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

For checking if a String is a number (and don't forget to include quotation marks if you're going to use that code exactly), look at str.isdigit().

I.e.

>>> 'corn'.isdigit()
False
>>> '123'.isdigit()
True
Celeo
  • 5,583
  • 8
  • 39
  • 41
1

This may not be the prettiest solution but it's able to respond when the delimiter size changes (say you want to track another number between corn and broccoli) and also allows it to grow beyond a set of three lists if you want.

lst = ["corn", 14, 2, 500, "broccoli", 2, 10, 1400, "potato", 2, 14, 7]
string_indices = [index for (index, value) in enumerate(lst) 
                  if isinstance(value, str)]

# We want to include the last group as well
string_indices.append(len(lst))

sublists = [lst[string_indices[x]:string_indices[x+1]] 
            for x in xrange(len(string_indices) - 1)]

lst1, lst2, lst3 = sublists

At the end, sublists is equal to:

[['corn', 14, 2, 500], ['broccoli', 2, 10, 1400], ['potato', 2, 14, 7]]                                                                                  

...and it unpacks into the three lists as shown above.

Kevin London
  • 4,628
  • 1
  • 21
  • 29
1

This is hideous but will get the job done for ya.


l = ["corn", 14, 2, 500, "broccoli", 2, 10, 1400, "potato", 2, 14, 7, 5, 6, 7, "carrot"]
out = []
for i in xrange(0, len(l)):
    if isinstance(l[i], str):
        tmp = []
        tmp.append(l[i])
        i += 1
        while (i < len(l)) and isinstance(l[i], int) :
            tmp.append(l[i])
            i += 1
        out.append(tmp)
In [41]: out
Out[41]:
[['corn', 14, 2, 500],
 ['broccoli', 2, 10, 1400],
 ['potato', 2, 14, 7, 5, 6, 7],
 ['carrot']]

reptilicus
  • 10,290
  • 6
  • 55
  • 79
1

There are two problems in the single line of code that you posted

  1. it's likely that you want to use strings rather than generic objects in your list

  2. list is a python function that creates a list from a sequence or an iterable and deserves to be let on its own, so we name your list a_list

What follows is based on a single assumption, that you want to split on each string and only on strings

a_list = ['corn', 14, 2, 500, 'broccoli', 2, 10, 1400, 'potato', 2, 14, 7]
# initialize an empty list (I can do it in other ways, but I want
# to show you an use of the `list` builtin function) and a counter `n`

list_of_sublists = list() # the function 'list' is called with no arguments
n = 0

# iterate for the index and the corresponding element of the list
for i, elt in enumerate(a_list):
    # when we reach the second string in the list we append the sublist
    # from the previous beginning `n=0`, do you remember? up to the current
    # index, that in python is _excluded_ from the sublist, and finally we
    # update the index for the start of the next sublist
    # NOTA BENE the SECOND string triggers the saving of the FIRST sublist
    if i and type(elt) == str:
        list_of_sublists.append(a_list[n:i])
        n = i
    # and of course the code above is triggered for the third, the ...,
    # the last string in the list

# but when we reach the end of the loop, having found that there are no
# further strings past the last one ;-) we have still the last sublist,
# the one that starts with the last string, that waits for being appended
# so here we do this last append

list_of_sublists.append(a_list[n:])

print list_of_sublists

Someone will object that the test type(elt) == str will fail for objects that are subclassed from str, or that quacks like a str, but I assume that you have 'nuff stuff to think about already...

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
gboffi
  • 22,939
  • 8
  • 54
  • 85
  • You know, if someone has a question due to being a beginner at coding, it might not be the most productive to sit on a pedestal. Nobody else felt it was needed to talk crap about how i am asking a beginners question. – Pewkie Oct 14 '14 at 00:52
  • @Pewkie I stand corrected. I admit that I was upset by the failure of your question to show effort toward a solution and that I over reacted, but if you're a beginner at coding the limits I had perceived in your question are absolutely justified. My bad I didn't understand. May I ask if you've have studied my answer? I think that it deserves your attention despite the offensive wording that I've used. – gboffi Oct 14 '14 at 17:56