Home > database >  Shorter solution to append split output
Shorter solution to append split output

Time:12-10

I have a list that need to be split and appended to different lists. input_data contains coordinates which are separated by a comma:

x1, y1, x2, y2 = [], [], [], []

for entry in input_data:
    a1, b1 = entry[0].split(",")
    a2, b2 = entry[1].split(",")     
    x1.append(a1)
    y1.append(b1)
    x2.append(a2)
    y2.append(b2)    

I also tested the _ variable as a temporary variable:

for entry in input_data:
   x1.append(_), y1.append(_) = entry[0].split(",")
   x2.append(_), y2.append(_) = entry[1].split(",") 

But this doesn't work.

CodePudding user response:

Another possible option is to transform each entry into something a bit more manageable, and then transpose:

preprocessed = [(*entry[0].split(","), *entry[1].split(",")) for entry in input_data]
result = list(zip(*preprocessed))

For a sample list

input_data = [('a,b', 'c,d'), ('e,f', 'g,h'), ('i,j', 'k,l')]

this appears to produce the desired result:

[('a', 'e', 'i'), ('b', 'f', 'j'), ('c', 'g', 'k'), ('d', 'h', 'l')]
  • Related