-1

I'm trying to work out a way to find out if a variable consists of one item or multiple items. I know that seems rather vague but hopefully the below will shed some light.

I've tried a few things, initially I thought the item looked like it was either a string or a list but using if isinstance(variable, basestring) produces a True on every value. I tried to check the length using len() but of course as they are strings I always get a count of each character in the string. I also tried if isinstance(variable, list) but of course this always had a False.

I'm trying to print each item on its own, below is some sudo code and test data.

variable = ["[u'cheese']", "[u'grapes', u'oranges']", "[u'apple']"]

for item in variable:
    if isinstance(item, list):
        for i in item:
            print i
    else:
        print item

Of course as mentioned this code does not work and I'm not sure how to tackle this. Any help would be appreciated.

pp_
  • 3,435
  • 4
  • 19
  • 27
iNoob
  • 1,375
  • 3
  • 19
  • 47
  • 4
    You have a list of strings, not a list of lists – OneCricketeer Mar 05 '16 at 16:03
  • Yes, I can see that but doing a simple `for i in variable: print i` produces [u'grapes', u'oranges'] or [u'apple'] I want each item to print on its own – iNoob Mar 05 '16 at 16:05
  • 3
    Each item _is_ printing on its own. Each one is a single string. Why are you using strings instead of lists? – ChrisGPT was on strike Mar 05 '16 at 16:06
  • 1
    In order to make `isinstance(variable, list)` evaluate to true, you need a list, not a string. `[2]` is a list... `"[2]"` is a string... See the quotes? That's your problem – OneCricketeer Mar 05 '16 at 16:10
  • 2
    you may want to check this: http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python and "ast.literal_eval()" function – MaxU - stand with Ukraine Mar 05 '16 at 16:11
  • @MaxU useful, but the list here is already flat – OneCricketeer Mar 05 '16 at 16:12
  • In your case, to work with list of strings is more complicated than with list of lists. Check out pp_'s answer for the list of lists and mine for the list of strings. – Ian Mar 05 '16 at 16:23
  • Thanks for the down vote, always appreciated with no comment on why – iNoob Mar 05 '16 at 16:23
  • 1
    @iNoob I believe this is a valid question, upvoted. Your case just happen to be quite "unusual" for Python case.. especially with `[[],[],[,]]` square brackets inside square brackets, it is normal for people to expect that it is supposed to be list of lists rather than list of strings. It is a valid question, nevertheless. – Ian Mar 05 '16 at 16:24

4 Answers4

3

If for some reason you truly need to process strings in this way you can use ast.literal_eval to get real lists from your strings:

import ast

for item in ["[u'cheese']", "[u'grapes', u'oranges']", "[u'apple']"]:
    for food in ast.literal_eval(item):
        print(food)
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
1

Use actual lists instead of strings. Then it should be easy to loop through the items.

variable = [[u'cheese'], [u'grapes', u'oranges'], [u'apple']]

for item in variable:
    for x in item:
        print x

Output:

cheese
grapes
oranges
apple
pp_
  • 3,435
  • 4
  • 19
  • 27
  • 1
    Thanks for the reply, but if you used the data I supplied youd see that this prints each character on its own, not as a word. – iNoob Mar 05 '16 at 16:21
  • 2
    @iNoob The question is why you have this rather odd input data in the first place. This could be a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – pp_ Mar 05 '16 at 16:26
1

Your variable seems to be a list of string:

variable = ["['cheese']", "[u'grapes', u'oranges']", "[u'apple']"]

But in that string you may have multiple items. Thus, you may need to do some string parsing. For your simple case, if you only want to count the number of element per list, the simplest is by counting the number of comma + 1. So I recommend to use simple string.split(',') to print the elements one by one:

variable = ["['cheese']", "[u'grapes', u'oranges']", "[u'apple']"]
for var in variable:
    words = var.split(',')
    for w in words:
        printedword = w.replace('u\'','').replace('\'','').replace(']','').replace('[','').strip()
        print(printedword)

Result:

cheese
grapes
oranges
apple

It would have been a lot easier to work with if your variable is list of lists though. Check out pp_ answer for that.

Community
  • 1
  • 1
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Thanks for taking the time to read the question and actually use the data in context. Appreciated Ian, far to often you get people on here that just want to abuse op for not doing something they way they would do something. rather than actually looking at the question, for instance, im not asking how to not use a list of strings and how to use a list of lists. – iNoob Mar 05 '16 at 16:25
  • Yes I agree, it would be easier if it was a list of lists, but as mentioned I dont have a list of lists. Thanks again – iNoob Mar 05 '16 at 16:26
  • Its a shame you cant share solutions :( – iNoob Mar 05 '16 at 16:54
0
>>> variable = ["[u'cheese']", "[u'grapes', u'oranges']", "[u'apple']"]
>>> for i in variable:
...     for j in i.lstrip('[').rstrip(']').split(','):
...         print j.lstrip(" ").lstrip("u'").rstrip("'") 
... 
cheese
grapes
oranges
apple
>>> 
caot
  • 3,066
  • 35
  • 37