Lumi Akimova
Lumi Akimova

Reputation: 3027

Can be done more pythonic?

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.

Upvotes: 1

Views: 158

Answers (4)

Francis Colas
Francis Colas

Reputation: 3647

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]

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

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)

Upvotes: 0

Zach Gates
Zach Gates

Reputation: 4155

A list comprehension is what you're looking for.

[[list(z) for z in y] for y in x]

Upvotes: 5

Cory Kramer
Cory Kramer

Reputation: 117926

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']]]

Upvotes: 2

Related Questions