Home > OS >  In Python, I want to add a number to each element in a list, but I get [[0,1],2] instead of [0,1,2].
In Python, I want to add a number to each element in a list, but I get [[0,1],2] instead of [0,1,2].

Time:01-12

I have

listB=[[0,1],[1,2]]

listall=[0,1,2,3]

For each element in listB, I want to extend it to a length-3 element by adding a number that is in listall but not in this element. My desired output is the following list:

listC=[[0,1,2],[0,1,3],[1,2,3]]

As a first step, I tried the following code:

import numpy as np

listB=[[0,1],[1,2]]
listall=range(4)
listC=[]
for b in listB:
    difb=set(listall)-set(b)
    for i in difb:
        listC.append([b,i])
print(listC)

However, the output I got is:

[[[0,1],2],[[0,1],3],[[1,2],0],[[1,2],3]]

This is far from what I wanted. As each element in this output list has a subarray nested in it, also the numbers in each element are not ordered. I need to at least turn it to [[0,1,2],[0,1,3],[0,1,2],[1,2,3]] first (and then get rid of the duplicates). What's the fastest (most efficient) way to achieve it? Thanks!

CodePudding user response:

You need to unpack the items in b when creating the new list

listC.append([*b,i])

or if its easier to understand, add a new list with i to list b

listC.append(b   [i])

CodePudding user response:

If you want to keep only unique lists (unique in the sense that the exact set of its elements are not found elsewhere in listC) in listC, then you might want to consider replacing

listC.append([b,i])

with

new = set([*b, i])
if new not in listC:
    listC.append(new)

Then the final output becomes:

>>> listC = [list(c) for c in listC]
[[0, 1, 2], [0, 1, 3], [1, 2, 3]]
  •  Tags:  
  • Related