简体   繁体   中英

How to select an integer randomly from a list containing integers as well as other objects?

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))

您可以过滤非整数项目;

inp2 = ramdom.choice([x for x in data if isinstance(x, int)])

尽管它与Neo的回答几乎相似,但是您也可以尝试以下操作:

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

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
>>> 
random.choice([i for i in data[-5:] if isinstance(x, int)])

通过isinstance()检查数据[-5:]的类型更安全。

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:])

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM