0

I have my list:

l = [["1","2","3",["4","a"],"5"], ["6",["7"],"8","9"]]

I want it to become:

l = ["1","2","3","4-a","5","6","7","8","9"]

To finally transform it to a string separated by ";"

my_string: 1;2;3;4-a;5;6;7;8;9

I tried using the flat_list function but it's not doing what I want because it separates the "4" and "a" not how I want it:

def flat(sequence):
    result = []
    if isinstance(sequence, list):
        for item in sequence:
            if isinstance(item, list):
                result += flat(item)
            else:
                result.append(item)
        return result
    else:
        return sequence

It makes this:

l = [["1","2","3","4","a","5"],["6","7","8","9"]]

(By the way, if you have a better option of transforming the list into the string I want, feel free to explain it to me, I would be pleased of any solution)

1 Answers1

2

If there is no more requirement, you could do some easy list comprehension:

l = [["1","2","3",["4","a"],"5"], ["6",["7"],"8","9"]]

resultList = ["-".join(j) if type(j) == list else j for i in l for j in i] 
# ['1', '2', '3', '4-a', '5', '6', '7', '8', '9']
print(";".join(resultList)) 
# 1;2;3;4-a;5;6;7;8;9
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • Thank you! It works with numbers or words of one character, how would you do it with words like: [["hello","bye","hello",["bye","hello"],"bye"], ["hello",["bye"],"hello","bye"]] – queenbegop777 Jul 05 '20 at 14:15
  • @queenbegop777 I've edited my code,check it.I make a careless mistake in my code. – jizhihaoSAMA Jul 05 '20 at 14:20