1

I have a list

data=['_','_','A','B','C',1,2,3,4,5] 

I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members

Here's what i tried but it throws an error retrieving the other members:

inp2=int(random.choice(data)) 

6 Answers 6

4

You can filter the non-integer items;

inp2 = ramdom.choice([x for x in data if isinstance(x, int)]) 
Sign up to request clarification or add additional context in comments.

2 Comments

"The list keeps getting modified so i cant just simply choose from the last 5 members"
@user3650037 Happy to help:)
2

Though it is almost similar to the answer of Neo, you can also try this:

inp2 = random.choice(filter(lambda d: isinstance(d, int), data)) 

Comments

0

To create a list of last 5 elements.

>>> from random import choice >>> data=['_','_','A','B','C',1,2,3,4,5] >>> l = len(data) >>> data[(l-5):l] [1, 2, 3, 4, 5] >>> k = data[(l-5):l] >>> choice(k) 5 >>> choice(k) 2 >>> 

Comments

0
random.choice([i for i in data[-5:] if isinstance(x, int)]) 

It is more safe for check type of data[-5:] by isinstance().

Comments

0

Try this.

import operator inp2 = random.choice(filter(operator.isNumberType, data)) 

For this specific problem selecting last 5 elements also a good solution.

inp2 = random.choice(data[5:]) 

1 Comment

Your first solution will filter the numeric types, as in int, float, long etc. But OP needs only int types here.
0

I think the best solution would be creating another list, where would be just int values you want to pick from. I don't know your specified assignment, but for example if you have a method for adding to your list, just add there:

def add(self, element): self.data.append(element) if type(element) == int: self.data_int.append(element) 

and then just use:

def get_value(self): return random.choice(self.data_int) 

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.