I am new to python and don't know the best way to do this.
I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms. Here's some code:
offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]
So my set of combined points should be
[( 1, 5),( 1, 4),( 1, 6),( 2, 5),( 0, 5),
( 3, 3),( 3, 2),( 3, 4),( 4, 3),( 2, 3),
( 8, 7),( 8, 6),( 8, 8),( 9, 7),( 7, 7)]
I'm not able to use NumPy or any other libraries.
In Python, we can easily add a tuple to a list with the list extend() function. You can also use the += operator to append the items of a tuple to a list in Python. When working with collections of data in Python, the ability to add and remove elements from an object easily is very valuable.
Add/insert items to tuple If you want to add new items at the beginning or the end to tuple , you can concatenate it with the + operator as described above, but if you want to insert a new item at any position, you need to convert a tuple to a list. Convert tuple to list with list() . Insert an item with insert() .
Creating a TupleA tuple in Python can be created by enclosing all the comma-separated elements inside the parenthesis (). Elements of the tuple are immutable and ordered. It allows duplicate values and can have any number of elements. You can even create an empty tuple.
result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]
For more, see list comprehensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With