Get a element from list, from pair of 3

Question:

Hello I have a list in which elemnets are in pair of 3 list given below,

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']

in above list elements are coming in pair of 3 i.e. (”, ”, ‘5000’) one pair, (”, ‘2’, ”) second pair, (‘mm-dd-yy’, ”, ”) third pair and so on.

now i want to check ever 3 pairs in list and get the element which is not blank.

(”, ”, ‘5000’) gives ‘5000’

(”, ‘2’, ”) gives ‘2’

(‘mm-dd-yy’, ”, ”) gives ‘mm-dd-yy’

and if all three are blank it should return blank i.e.

(”, ”, ”) gives ” like last 2 pair in list

so from the above list my output should be:

required_list = ['5000','2','1000','mm-dd-yy','15','dd/mm/yy','3','200','2','mm-dd-yy','','']
Asked By: Mohit

||

Answers:

as it is fixed you have to create 3 pairs each time you can do with for loop by specifying step in range(start,end,step)

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']
res1=[]
for i in range(0,len(labels),3):
    res1.append(labels[i]+labels[i+1]+labels[i+2])
print(res1)

#List Comprehension
res2=[labels[i]+labels[i+1]+labels[i+2] for i in range(0,len(labels),3)]

print(res2)

Output:

['5000', '2', '1000', 'mm-dd-yy', '15', 'dd/mm/yy', '3', '200', '2', 'mm-dd-yy', '', '']
Answered By: Yash Mehta

Iterate over a 3 sliced list and then get the first non-null element with next.

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']
length = len(labels)
list_by_3 = [labels[i:i+3] for i in range(0, length, 3)]

required_list = []
for triplet in list_by_3:
  if triplet == ["","",""]:
    required_list.append("")
  else:
    required_list.append(
      next(i for i in triplet if i)
    )
>>> required_list
['5000', '2', '1000', 'mm-dd-yy', '15', 'dd/mm/yy', '3', '200', '2', 'mm-dd-yy', '', '']
Answered By: scr

I think this should give you the required result. Not ideal performance but gets the job done and should be pretty easy to follow

    labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']

    def chunks(ls):
        chunks = []

        start = 0
        end = len(ls)
        step = 3
        for i in range(start, end, step):
            chunks.append(ls[i:i+step])

        return chunks

    output = []
    for chunk in chunks(labels):
        nonEmptyItems = [s for s in chunk if len(s) > 0]
        if len(nonEmptyItems) > 0:
            output.append(nonEmptyItems[0])
        else:
            output.append('')

    print(output)
Answered By: Curtis Cali