Home > Mobile >  Change the format of list in list into specific order in python
Change the format of list in list into specific order in python

Time:11-20

I have this type of nested list data.

array =[
['PRODUCT NAME PACK', 'BAIGAM KOT', 'FIAZ BAGH', 'OLD ANARKALI', 'SULTAN PURA', 'TEZAB AAHATA', 'GHORAY SHAH', 'KOT KHAWAJA SAEED']
['002188', 0, 0, 0, 0, 0, '2', '3']
['PRODUCT NAME PACK', 'BAGHBAN PURA', 'GAWAL MANDI', 'OLD ANARKALI', 'MAYO HOSPITAL', 'GARHI SHAHU BAZAR', 'BILAL GUNJ', 'LADY WELLINGTON HOSPITAL']
['002188', '3', 0, 0, 0, 0, 0, 0]
['008999', 0, 0, 0, 0, '1', 0, 0]
['012961', 0, 0, 0, 0, 0, '3', 0]
]

Want this type of output from this list.

array =[
[['PRODUCT NAME PACK', 'BAIGAM KOT', 'FIAZ BAGH', 'OLD ANARKALI', 'SULTAN PURA', 'TEZAB AAHATA', 'GHORAY SHAH', 'KOT KHAWAJA SAEED']
['002188', 0, 0, 0, 0, 0, '2', '3']]
[['PRODUCT NAME PACK', 'BAGHBAN PURA', 'GAWAL MANDI', 'OLD ANARKALI', 'MAYO HOSPITAL', 'GARHI SHAHU BAZAR', 'BILAL GUNJ', 'LADY WELLINGTON HOSPITAL']
['002188', '3', 0, 0, 0, 0, 0, 0]
['008999', 0, 0, 0, 0, '1', 0, 0]
['012961', 0, 0, 0, 0, 0, '3', 0]]
]

CodePudding user response:

This would work:

array = [
    [
        "PRODUCT NAME PACK",
        "BAIGAM KOT",
        "FIAZ BAGH",
        "OLD ANARKALI",
        "SULTAN PURA",
        "TEZAB AAHATA",
        "GHORAY SHAH",
        "KOT KHAWAJA SAEED",
    ],
    ["002188", 0, 0, 0, 0, 0, "2", "3"],
    [
        "PRODUCT NAME PACK",
        "BAGHBAN PURA",
        "GAWAL MANDI",
        "OLD ANARKALI",
        "MAYO HOSPITAL",
        "GARHI SHAHU BAZAR",
        "BILAL GUNJ",
        "LADY WELLINGTON HOSPITAL",
    ],
    ["002188", "3", 0, 0, 0, 0, 0, 0],
    ["008999", 0, 0, 0, 0, "1", 0, 0],
    ["012961", 0, 0, 0, 0, 0, "3", 0],
]

outer = []
for item in array:
    if "PRODUCT NAME PACK" in item:
        inner = []
        outer.append(inner)
    inner.append(item)

print(outer)

That gives me:

➜  nested python main.py 
[[['PRODUCT NAME PACK', 'BAIGAM KOT', 'FIAZ BAGH', 'OLD ANARKALI', 'SULTAN PURA', 'TEZAB AAHATA', 'GHORAY SHAH', 'KOT KHAWAJA SAEED'], ['002188', 0, 0, 0, 0, 0, '2', '3']], [['PRODUCT NAME PACK', 'BAGHBAN PURA', 'GAWAL MANDI', 'OLD ANARKALI', 'MAYO HOSPITAL', 'GARHI SHAHU BAZAR', 'BILAL GUNJ', 'LADY WELLINGTON HOSPITAL'], ['002188', '3', 0, 0, 0, 0, 0, 0], ['008999', 0, 0, 0, 0, '1', 0, 0], ['012961', 0, 0, 0, 0, 0, '3', 0]]]

  • Related