0

Seems to be a simple question but I tried a dozen of possibilities without result. I just want to change ['55.00', ['CHF', '0.00']] into [['55.00'], ['CHF'], ['0.00']] or:

var1 = "55.00"
var2 = "CHF"
var3 = "0.00"

As an example, I tried:

mik = ['55.00', ['CHF', '0.00']]
mik = [s.split(',') for s in ','.join(mik).split(',')]

Result:[['C'], ['H'], ['F'], [' '], ['0'], ['.'], ['0'], ['0']]

What could be the solution in my situation?

hacking_mike
  • 1,005
  • 1
  • 8
  • 22

4 Answers4

0

You can unpack your list. This answer assumes that you always have RHS of the format [el, [el2, el3]]

>>> var1, (var2, var3) = ['55.00', ['CHF', '0.00']]
>>> var1
'55.00'
>>> var2
'CHF'
>>> var3
'0.00'
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
0
mik = ['55.00', ['CHF', '0.00']]
new_lst = []

for item in mik:
    if type(item) == list:
        for x in item:
            new_lst.append(x)
        continue
    new_lst.append(item)
print(new_lst)

Simply you iterate over the list and if you found the item is itself a list you iterate over it's items and append them to your new_lst object and if it is not a list you just append it.

The output from the above code:

['55.00', 'CHF', '0.00']
Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18
0

What you want is basically to flatten your list if I understood correctly. This question might be helpful.

from collections.abc import Iterable

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

mik = flatten(['55.00', ['CHF', '0.00']])
rikyeah
  • 1,896
  • 4
  • 11
  • 21
0

If you only have these 3 elements, you could do this:

mik = ['55.00', ['CHF', '0.00']]

mik[1:] = mik[1]

print(mik) # ['55.00', 'CHF', '0.00']

If there are multiple sublists and/or more than one level of nesting, you can use the same approach in a loop:

for i,_ in enumerate(mik):
    while isinstance(mik[i],list):
        mik[i:i+1] = mik[i]
Alain T.
  • 40,517
  • 4
  • 31
  • 51