2

I have the following list;

lst = ["['atama', 'karada', 'kami', 'kao', 'hitai', 'me', 'mayu', 'mabuta', 'matsuge', 'hana']", 
       "['head', 'body', 'hair', 'face', 'forehead', 'eye', 'eyebrow', 'eyelid', 'eyelash', 'nose']"]

I need to get the contents of each item set as a list, so that I can print the items individually. Eg.

for item in lst:
    for word in list(item):
        print word

>>

atama
karada
kami
kao
etc.

Any ideas how I could format the str(item)|s to lists once again?

2
  • Is the goal to just take lst and create a list containing all of the items within the lists in lst? Commented May 17, 2012 at 8:52
  • Sorry for not being clear, the goal is to create lists (one, two) containing the contents of the strings contained in the list.. Wow I'm bad with words. Commented May 17, 2012 at 8:58

3 Answers 3

3
>>> import ast
>>> L = ["['atama', 'karada', 'kami', 'kao', 'hitai', 'me', 'mayu', 'mabuta', 'matsuge', 'hana']", 
       "['head', 'body', 'hair', 'face', 'forehead', 'eye', 'eyebrow', 'eyelid', 'eyelash', 'nose']"]
>>> for item in L:
        for word in ast.literal_eval(item):
            print word


atama
karada
kami
kao
hitai
me
mayu
mabuta
matsuge
hana
head
body
hair
face
forehead
eye
eyebrow
eyelid
eyelash
nose
Sign up to request clarification or add additional context in comments.

Comments

1

I can think of several methods:

1) Manually extract each list item:

lst = [[item.strip()[1:-1] for item in element[3:-3].split(',')] for element in lst]

2) Use eval:

lst[:] = eval(lst[0]), eval(lst[1])

3) Use json:

import json
lst = [json.loads(i) for i in lst]

Methods 1 or 3 are preferred. eval is unsafe, as any string passed to eval will be (surprise, surprise) evaluated. Only use eval if you have complete control over what is being passed to it.

4) Another solution that occured to me, use regular expressions:

import re
lst = [re.findall("['\"](\w+)['\"]", item) for item in lst]

2 Comments

The first option in this worked well :) The only thing is, I get string items as follows : "'karada" : Is there a way to prevent "'" from ocuring at the start of each subsequent item? Thank you :)
Spot on! Thanks heaps for your help, once again! :)
0
(one, two) = (list(lst[0]), list(lst[1]))

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.