I meet such an issue: I want to store a number of 2-D pixels like [2,3], [4,5], and [7,9] into a set like ([2,3], [4,5], [7,9]). So that we know if a pixel is processed.
My code is like:
stack = ()
pixel = [2, 3]
stack = stack (pixel)
pixel = [4, 5]
stack = stack (pixel)
# I want stack to be ([2,3],[4,5])
if [4,5] in stack:
pass
else:
process this pixel
It shows an error:
TypeError: can only concatenate tuple (not "list") to tuple: line 3:stack = stack (pixel)
Can anyone help to solve this issue to store [x,y] in a set? like ([x1,y1], [x2,y2], ... [xn, yn])
CodePudding user response:
There are several things going on here:
First of all, stack = ()
creates a tuple:
a = ()
print(type(a))
results in:
<class 'tuple'>
Note that a tuple
allows duplicate elements, while a set
's elements are distinct.
In addition, you can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.
You can however add tuples to the set as tuples are imutable:
a = set()
pixel = (2, 3)
a.add(pixel)
pixel = (4, 5)
a.add(pixel)
print(a)
results in:
{(2, 3), (4, 5)}
CodePudding user response:
Tuple always needs a comma even if you do not want to store more than two things:
stack = stack (pixel,)
CodePudding user response:
You wrote almost everything right. You forgot to add the comma to the tuple. A comma always goes after the tuple ,
. The comma is required otherwise Python would treat the single tuple as any string.
stack = ()
pixel = [2, 3]
stack = stack (pixel,)
pixel = [4, 5]
stack = stack (pixel,)
# I want stack to be ([2,3],[4,5])
if [4,5] in stack:
pass
else:
process this pixel