如何将含25个元素的列表随机无重复地分成5组?
Hey there! The problem you're facing makes total sense—using random.sample(l, 5) repeatedly on the original list will definitely lead to duplicate elements, since you never remove the already-selected items from the pool. Let's go over two solid solutions to fix this, starting with the most efficient one.
The Shuffle-and-Slice Method (Recommended)
Instead of looping to sample and remove elements, the cleanest approach is to first shuffle the entire list randomly, then split it into equal chunks. This guarantees no overlaps and ensures every group is fully random.
Here's the Python code to implement this:
import random # Replace with your actual 25-element list original_list = [i for i in range(1, 26)] # Create a copy to avoid modifying the original list (optional but safe) shuffled_list = original_list.copy() random.shuffle(shuffled_list) # Split into 5 groups of 5 elements each groups = [shuffled_list[i*5 : (i+1)*5] for i in range(5)] # Verify the result for group_num, group in enumerate(groups, 1): print(f"Group {group_num}: {group}")
Key Notes:
random.shuffle()reorders the list in place—using.copy()first keeps your original list intact if you need it later.- The list comprehension splits the shuffled list into consecutive slices of 5 elements. Since the entire list is randomized upfront, each group is a unique, random subset.
The Sample-and-Remove Method (Loop-Based Approach)
If you want to stick closer to your original idea of sampling and removing elements, you can work with a temporary copy of the list and remove sampled items each time. This works great for small lists like yours, though it's less efficient than the shuffle method.
Here's how to do it:
import random original_list = [i for i in range(1, 26)] temp_list = original_list.copy() groups = [] for _ in range(5): # Sample 5 elements from the remaining items current_group = random.sample(temp_list, 5) groups.append(current_group) # Remove each sampled element from the temporary list for item in current_group: temp_list.remove(item) # Check the groups for group_num, group in enumerate(groups, 1): print(f"Group {group_num}: {group}")
Key Notes:
- We use a temporary list so we don't alter the original.
list.remove()finds and deletes the first occurrence of each item—this works as long as your list has no duplicate elements (which I assume is the case here).
Either method will solve your duplicate sample problem—pick the one that fits your code style best!
内容的提问来源于stack exchange,提问作者user9369411

