Home > Blockchain >  I have a list [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)]. After every element i want to insert
I have a list [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)]. After every element i want to insert

Time:06-07

I want to insert element (x,y) in such a way that the list [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)] containing x and y cordinates becomes [(620.9, 234.5),(621.9, 234.5), (591.6, 205.4), (592.6, 205.4), (823.4, 205.8),(824.4, 205.8)].

CodePudding user response:

It's just a simple for-loop... unless I've misunderstood something?

def foo(lst):
    res = []
    for a, b in lst:
        res  = [(a, b), (a 1, b)]
    return res

you could do it as a list comprehension if you want:

sum([[(a, b), (a 1,b)] for a, b in lst], [])

and as @cards mentions, there is itertools:

import itertools
list(itertools.chain(*[[(a, b), (a 1, b)] for a, b in lst]))

I would probably use the first version.

CodePudding user response:

A recursive approach

def xshift(coordinates):
    out = []
    if not coordinates:
        return out

    x, y = p = coordinates[0]
    out.extend((p, (x 1, y)))
    out.extend(xshift(coordinates[1:]))
    return out

print(xshift(lst))

CodePudding user response:

From what I could understand in your example you want to add an element in your list that is the previous element added whit an offset, here ( 1, 0) ?

If so you could do it like

>>> element = (1, 0)
>>> input = [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)]
>>> output = []
>>> for value in input:
...     output.append(value)
...     output.append((value[0]   element[0], value[1]   element[1]))
...
>>> output
[(620.9, 234.5), (621.9, 234.5), (591.6, 205.4), (592.6, 205.4), (823.4, 205.8), (824.4, 205.8)]

But again your original question lacks of explanations

CodePudding user response:

Try this


lst = [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)]
new_lst = []

for a in lst:
    new_lst.append(a)
    new_lst.append((a[0] 1,a[1]))

print(new_lst)

Another using Numpy

import numpy as np
lst = np.array([(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)])

new_lst = []
for a in lst:
    new_lst.extend((tuple(a),tuple(a [1,0])))


print(new_lst)

OUTPUT [(620.9, 234.5), (621.9, 234.5), (591.6, 205.4), (592.6, 205.4), (823.4, 205.8), (824.4, 205.8)]

Another One.


lst = [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)]
lst = [(a,(a[0] 1,a[1]))for a in lst]
new_lst = []
for a in lst:
    new_lst.extend(a)
print(new_lst)

You can also make this in a short way, But I suggested one of the above.

lst = [(620.9, 234.5), (591.6, 205.4), (823.4, 205.8)]
new_lst = []
[new_lst.extend((a,(a[0] 1,a[1]))) for a in lst]
print(new_lst)
  • Related