I have a question ,I have one list : country = [ Australia , america , England , Spain] If i want to choose 2 of them random for (List A) and choose 2 of them random for (List B ) and values of two lists arent same (not equal to gether) Can You say which code should i write
Asked
Active
Viewed 50 times
-1
-
1[`random.sample`](https://docs.python.org/3/library/random.html#random.sample) four items and then split them into two lists… – deceze Nov 07 '21 at 11:58
-
`pairings = list(itertools.zip_longest(*[iter(random.sample(country, k=len(country)))] * 2))`. – ekhumoro Nov 07 '21 at 13:11
2 Answers
0
You can use random.sample
:
country = ['Australia', 'america', 'England', 'Spain']
import random
random.sample(country, k=2)
If you want to split in two:
A = set(country)
B = random.sample(A, k=2)
A = list(A.difference(B))
output:
>>> A
['England', 'america']
>>> B
['Spain', 'Australia']
alternative: random.shuffle
(modifies the initial list)
import random
random.shuffle(country)
A = country[:2]
B = country[2:]

mozway
- 194,879
- 13
- 39
- 75
-
1alternative: [`random.sample(country, k=len(country))`](https://docs.python.org/3/library/random.html#random.sample) (doesn't modify the initial list) – Olvin Roght Nov 07 '21 at 12:14
-
@Olvin, yes so many possibilities ;) the downside is that it makes a copy. – mozway Nov 07 '21 at 12:16
-
I'd say it's a pros of it *(if initial data modification is not allowed)* – Olvin Roght Nov 07 '21 at 12:17
-
@Olvin Roght that would give you the same list as the original (4 entries) but shuffled. Why would that be of use in this scenario? – Marc-Alexandru Baetica Nov 07 '21 at 12:17
-
@Marc-AlexandruBaetica what Olvin suggested was just to replace the `shuffle`, then you still need to split in two ;) – mozway Nov 07 '21 at 12:19
-
1Gotcha. Seemed like he was talking about the `random.sample()` from the second example. Thanks for the clarification :) – Marc-Alexandru Baetica Nov 07 '21 at 12:21
-
-
-1
If I got you right, this could help
l = ['Australia' , 'america' , 'England' , 'Spain']
a = random.choices(l,k=2)
b=[]
for i in l:
if(i not in a):
b.append(i)
print(a)
print(b)
you can also try using sets

Olvin Roght
- 7,677
- 2
- 16
- 35