0

I have a custom class that I have made. I make a list out of that class:

grid = [] def make_grid(r,c): global grid grid = [grid_object(x,y) for x in range(r) for y in range(c)]#Thanks Adam make_grid(row, columns) #this makes the grid class grid_object(object):#Thanks Adam def __init__(self, x, y): self.x, self.y = x, y self.item = "Blank" self.tag = "Nothing" 

I want to hold a couple of grid's indexs for a side quest. Below I only showed one.

baby_grid = '' def baby_side_quest(): global grid global baby_grid baby_grid = [i for i, j in grid if j.tag == "Baby_Bear"] print baby_grid 

I can get the baby_grid as a list. Here the code just prints:

>>>[2]

But what I really want is just:

>>> 2

How can I do that without having to write baby_grid[0] everywhere?

I just added this little function.

def get_int_from_list(list_thing): return list_thing[0] 

I just wonder if there is a way that I don't know of that would make my code really concise. If you have a better way of doing this I'd love you see that code.

13
  • Yeah. I'm trying to avoid that. I have code that looks like this. elif grid[mama_grid[0]].enemy_killed_bool == False and grid[papa_grid[0]].enemy_killed_bool == False: grid[baby_grid[0]].been_here_text = "The baby bear is happy to still have both it's parents." Commented Jul 19, 2014 at 0:03
  • Then you should include that information in your question. Commented Jul 19, 2014 at 0:04
  • Ohh sorry. I'll add it now. Commented Jul 19, 2014 at 0:06
  • what exactly is the issue? Your function call would take as much to call as writing the list name and slicing. Commented Jul 19, 2014 at 0:14
  • I didn't actually think of writing a function until after I posted this question. I'd been working on it for an hour and I just didn't see that as a solution. Commented Jul 19, 2014 at 0:18

2 Answers 2

1

Will your baby_grid always only consist of one item? If so, you could simply do

baby_grid = [i for i, j in grid if j.tag == "Baby_Bear"][0] 
Sign up to request clarification or add additional context in comments.

1 Comment

if `j.tag != "Baby_Bear" you will get an index error and I think for a single value there are better ways to assign to a variable
1

I don't know how pythonic it is considered, but you could do that the old fashioned way:

for i, j in grid: if j.tag == "Baby_Bear": return i 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.