0

I'm trying to find a way to flatten my list so it outputs:

['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

So far my recursive function returns a new nested list of values with matched keys in a dictionary (using an old parameter list and a dictionary) is as follows:

l = ['won', 'too', 'three', 'fore', 'five', 'six', 'seven', 'ate', 'nein']
d = dict(won='one', too='two', fore='four', ate='eight', nein='nine')

def subst(l,d):
     if len(l) == 1:
         if l[0] in d:
             return d[l[0]]
         else:
             return l[0]
     else:
         return [d[l[0]] if l[0] in d else l[0]] + [subst(l[1:],d)]

So far I've been getting:

['one', ['two', ['three', ['four', ['five', ['six', ['seven', ['eight', 'nine']]]]]]]]

Is there any way I can flatten the list while keeping the recursive integrity of the function?

2 Answers 2

1
map(lambda x: d[x] if x in d else x,l)
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps you could add some description to your answer? Just posting a piece of code without explanation is rarely helpful.
1

You could omit the [] around the recursive subst() call.

Alternatively, you could do

def subst(l, d):
    return [d.get(i, i) for i in l]

which just iterates over the list and replaces each item with the respective entry in d, if any, creating a new list with the results.

If you'd rather keep the list, you could do

def subst(l, d):
    for n, i in enumerate(l):
        l[n] = d.get(i, i)

In a meanwhile deleted answer, someone asked about the race condition in [d[x] for x in l if x in d].

The race condition - in the case of a threaded program - consists of the separation between if x in d and the d[x] access. If another thread deletes exactly that entry in the dict referenced by d, the test succeeds, but the access nevertheless fails.

3 Comments

If I omit the [] around the recursive subst() call, I would get a TypeError: can only concatenate list (not "str") to list.
@user2559679: because your code doesn't always return a list... fix it
@Karoly Horvath Eureka! Thank you! The break/base case in the function returns a string. Just fixed it with some [].

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.