0

I try to import a list in python. However, I would like to customize my code in such a way, that the list will look like this:

['a', 'b', 'c']

instead of like this:

[["['a','b','c']"]]

The reason is that I have to compare if a list is in another list and it won't succeed when the list is not formatted well. The rest of the code looks like this:

def check(a1, a2):
    listA = []
    listB = []
    listA.append(a1)
    listB.append(a2)
    if listA in listB:
        print True
    else:
        print False
Max
  • 53
  • 1
  • 7
  • 4
    So, what is the question? – RedEyed Sep 10 '17 at 20:45
  • 1
    What do you mean by "formatted well" and how do strings and printing come into play here? – Andreas Grivas Sep 10 '17 at 20:48
  • Well, I would like that when I append a1 to listA, the list will be stripped (or something in a way like that) so that when I print listA, it looks like how I mentioned it above. So that I can compare the list with another list. – Max Sep 10 '17 at 20:48

2 Answers2

2

I'm not sure if I understand you correctly. Are you looking for this?

a = ['some', 'list', 'items']
print ', '.join(a)

This will print

some, list, items

But that probably won't solve what you're trying to do. Comparing two lists shouldn't involve print at all.

Pascal
  • 448
  • 3
  • 11
  • you're right, it's bad to convert list as string just to be able to use `in` in the string. So it kind of answers. – Jean-François Fabre Sep 10 '17 at 20:55
  • No I was not very clear in my question. I changed the question now. I want my list like this: ['a', 'b', 'c'] instead of like [["['a','b','c']"]]. Now, it looks like the last example, because I got that data from an .txt file. Do you understand what I mean? – Max Sep 10 '17 at 20:58
  • I'm still not entirely sure. So you have a string like `"['a', 'b', 'c']"` and you would like to turn that into the python list ['a', 'b', 'c'] ? Is that right? – Pascal Sep 10 '17 at 21:05
  • Yes that is right! – Max Sep 10 '17 at 21:37
  • 1
    Then use my answer and just take away the joining part – whackamadoodle3000 Sep 11 '17 at 23:31
0
import ast
weirdlist=[["['a','b','c']"]]
print(", ".join(ast.literal_eval(weirdlist[0][0])))

Try this. Formats it like this: a, b, c

EDIT: It seems like the question-asker wanted a list, not a string:

import ast
weirdlist=[["['a','b','c']"]]
print(ast.literal_eval(weirdlist[0][0]))
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44