'how to format a list by number and type of item in python
How to format a list in python? The code for the list would be something like this.
import random
nums = range(1, 11)
foods1 = ['pancake', 'pancake']
foods2 = ['pineapple pizza', 'pineapple pizza']
for num in nums:
for food1 in foods1:
list1 = [f"{num} {food1}"]
for food2 in foods2:
list2 = [f"{num} {food2}"]
alist = list1.append(list2)
blist = random.sample(alist, 12)
print (blist)
And I want the blist to listed with the same foods listed together and ordered by the number in front of them. The repeating foods in the two lists are intentional, the output of the list I would expect is like this: ['1 pancake', '3 pancake', '3 pancake', '5 pancake'... '3 pineapple pizza', '8 pineapple pizza', '9 pineapple pizza'] ordered by the numbers in front of them and separated by the kind of food they are.
Solution 1:[1]
Based on my understanding of your problem, here is a sleek solution, but please let me know if this is not what you intended to ask.
from random import sample
foods1 = ['pancake', 'pancake']
foods2 = ['pineapple pizza', 'pineapple pizza']
population = [f"{i} {food}" for i in range(1,11) for food in foods1]+[f"{i} {food}" for i in range(1,11) for food in foods2]
ans = sorted(sample(population,12), key=lambda x: x[0])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zircoz |
