Home > Software design >  How to make a nested list in python
How to make a nested list in python

Time:09-16

Suppose I have a 2 lists in my python script:

my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']

I want to iterate through other_list and create a nested list for 'bat's that adds '_' other_list item to a the 'bat' and puts it in a nested list:

 for item in other_list:
    for thing in my_list:
        if thing == 'bat':
            print(thing   '_'   item)

My desired outcome would be new_list = ['hat',['bat_A', 'bat_B', 'bat_C']] How would I achieve this? I tried the below, but it produces this: ['hat', 'hat', 'hat', ['bat_A', 'bat_B', 'bat_C']]

new_list = []
extra = []
for item in other_list:
    for thing in my_list:
        if thing == 'bat':     
            extra.append(thing   '_'   item)
        else:
            new_list.append(thing)
new_list.append(extra)

CodePudding user response:

OK, this is just my answer, but it seems to work. I think is clunky though, and I'm hoping for a better answer

my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']

new_list = []
extra = []

for item in other_list:
    for thing in my_list:
        if thing == 'bat':     
            extra.append(thing   '_'   item)
        else:
            if thing not in new_list:
                new_list.append(thing)
new_list.append(extra)

CodePudding user response:

I think will work

my_list = ['hat', 'bat']
other = ['A', 'B' , 'C']

new_list = []
extra = []

for item in my_list:
    if item == 'bat':
        for char in other:
            extra.append(item   '_'   char)
    else:
        new_list.append(item)
    
new_list.append(extra)
print(new_list)

CodePudding user response:

Try this:

>>> my_list = ['hat', 'bat']
>>> other_list = ['A', 'B', 'C']
>>> new_list=[my_list[0], [f'{my_list[1]}_{e}' for e in other_list]]
>>> new_list
['hat', ['bat_A', 'bat_B', 'bat_C']]

If your question (which is a little unclear) is just about reacting to 'bat' with a different reaction, you can do this:

my_list = ['hat', 'bat','cat']
other_list = ['A', 'B', 'C']

new_list=[]
for e in my_list:
    if e=='bat':
        new_list.append([f'{e}_{x}' for x in other_list])
    else:
        new_list.append(e)

>>> new_list
['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']

Which can be reduced to:

>>> [[f'{e}_{x}' for x in other_list] if e=='bat' else e for e in my_list]
['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']
  • Related