1

Here is my code:

for x in range(len(patterns)):
 for y in range(len(patterns[x])):
 patterns[x][y] = list(patterns[x][y])

It takes that as patterns:

[['oxooo', 'oxoxo'], ['oxooo']]

And gives that as patterns:

[[['o', 'x', 'o', 'o', 'o'], ['o', 'x', 'o', 'x', 'o']], [['o', 'x', 'o', 'o', 'o']]]

For me, looks not pythonic. Can it be done better? Output should be the same.

asked Mar 10, 2015 at 19:15
1

4 Answers 4

5

A list comprehension is what you're looking for.

[[list(z) for z in y] for y in x]
answered Mar 10, 2015 at 19:19
Sign up to request clarification or add additional context in comments.

Comments

2

Here is a general recursive solution that will achieve this for an arbitrary nesting of strings in lists.

def listify(x):
 if isinstance(x, str):
 return list(x)
 else:
 return [listify(i) for i in x]
>>> l = [['oxooo', 'oxoxo'], ['oxooo']]
>>> listify(l)
[[['o', 'x', 'o', 'o', 'o'], ['o', 'x', 'o', 'x', 'o']], [['o', 'x', 'o', 'o', 'o']]]
answered Mar 10, 2015 at 19:18

Comments

2

In your example you have a nested list in two levels. If that's always the case, you can use a list comprehension:

[[list(p) for p in pp] for pp in patterns]

If you don't know how many levels you have, you need to use a recursive function, for instance:

def expand_str(v):
 if isinstance(v, str): # basestring for python2
 return list(v)
 else: # assume that otherwise v is iterable
 return [expand_str(vv) for vv in v]
answered Mar 10, 2015 at 19:24

2 Comments

You basically just copied the two answers above you... and it took you 5+ minutes to do so. And in fact your second version doesn't even work.
Thanks for nicely pointing out the typo. When I wrote my message the two answers weren't above me; I actually wondered which approach would be correct for OP (because they're not equivalent) and decided in providing them both. I'll try to improve my typing skills, thanks for the advice.
0

If you want to modify the original list like your own code does use enumerate:

for ind, ele in enumerate(l):
 l[ind] = [list(s) for s in ele]
print(l)
[[['o', 'x', 'o', 'o', 'o'], ['o', 'x', 'o', 'x', 'o']], [['o', 'x', 'o', 'o', 'o']]]

You can also use map with enumerate:

for ind, ele in enumerate(l):
 l[ind] = list(map(list, ele))

You can also use the [:] syntax with a generator expression or list comprehension to change the original list:

l[:] = [list(map(list,ele)) for ele in l]
l[:] = (list(map(list,ele)) for ele in l)
answered Mar 10, 2015 at 19:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.