Operate List elements with another element in the same list

66 views Asked by At

im using python within grasshopper to construct komplex geometrical shapes, therefore i often work with lists and loops. I need to operate one list element with another, the next one in the same list, for instance. Does anyone have an alternative solution for my cause?

Cheers, Julian

So the way i figuered out, is to duplicate the list an shift/offset the elements in the list. (see in script below) I'm curious about an easier way, due to the number of lists in my scripts. Here's a little example.

TestList = [0,1,2,3,4,5]
TestList2 = TestList[-1:] + TestList [:-1]

TestList3 = []
for i, ii in zip(TestList,TestList2):
    TestList3.append(i + ii)
print(TestList3)

TestList3 = [5,1,3,5,7,9]

2

There are 2 answers

0
JonSG On

If you do this a lot, I would make a method out of it, then you can make the implementation as verbose as you like and keep the use clean:

def shifted_add(data):
    data_rotated = data[-1:] + data[:-1]
    retval = []
    for i, ii in zip(data, data_rotated ):
        retval.append(i + ii)
    return retval

data = [0,1,2,3,4,5]
print(shifted_add(data))

or

def shifted_add(data):
    data_rotated = data[-1:] + data[:-1]
    return [i + ii for i, ii in zip(data, data_rotated)]

data = [0,1,2,3,4,5]
print(shifted_add(data))

To clean it up a bit I might be tempted to yield the results like:

def shifted_add(data):
    data_rotated = data[-1:] + data[:-1]
    for i, ii in zip(data, data_rotated ):
        yield i + ii

data = [0,1,2,3,4,5]
print(list(shifted_add(data)))

or even:

def shifted_add(data):
    data_rotated = data[-1:] + data[:-1]
    yield from map(sum, zip(data, data_rotated))

data= [0,1,2,3,4,5]
print(list(shifted_add(data)))

Alternatively, if you don't like the method approach and just wanted something compact, I would go with:

data = [0,1,2,3,4,5]
data_rotated = data[-1:] + data[:-1]
data2 = list(map(sum, zip(data, data_rotated)))
print(data2)

Without getting too golfy, you technically don't need the dedicated variable and you should be able to do:

data = [0,1,2,3,4,5]
data2 = list(map(sum, zip(data, data[-1:] + data[:-1])))
print(data2)
0
Swifty On

There might be better ways to do it, but a simple comprehension can do the job:

SumList = [TestList[i-1] + TestList[i] for i in range(len(TestList))]