简体   繁体   中英

How to add 2 random numbers from a list together?

For example: list1 = [1,2,3,4,5,6]

I want to get 2 random numbers from this list and add them together:

3 + 2 for example.

For unique selections (sampling without replacement), you can make use of random.sample for selecting multiple random elements from the list and use the built-in sum .

>>> list1 = [1,2,3,4,5,6]
>>> from random import sample
>>> sum(sample(list1, 2))
7

A ValueError will be raised if you attempt to obtain a sample larger than your list (or more generally, population) size.

>>> sum(sample(list1, len(list1) + 1))
  File "D:\Anaconda\lib\random.py", line 315, in sample
    raise ValueError("Sample larger than population")
ValueError: Sample larger than population

For non-unique selections (sampling with replacement), a simple approach for small samples is just repeatedly calling random.choice for whatever sample size you require.

>>> from random import choice
>>> sum(choice(list1) for _ in range(2))
6

Obviously when sampling with replacement, the sample size can be larger than the size of the population.

>>> sum(choice(list1) for _ in range(1000))
3527

Here you have the solution, but what I'd like to tell you is that you wont go too far in programming by asking that kind of questions.

What you need to do before asking is to do some reflexion. for example, if I were you, I would have searched:

On google " python get random number list " > How do I randomly select an item from a list using Python? .

from random import choice

result = choice(list1) + choice(list1)

Good luck!

I guess that if you want distinct elements, you can use:

import random

sum(random.sample(list1, 2))

For taking random numbers from the list you can use

import random
random.choice()

In your case use

import random
list1 = [1,2,3,4,5,6]
sum=random.choice(list1)+random.choice(list1)

You should use the function:

from random import choice
a=(random.choice(list1))

'a' will now be a random number from the list

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