Python中random.shuffle返回None及生成3D点列表的问题
Hey there, let's break down your two Python issues one by one!
random.shuffle()返回None,拿不到打乱后的列表? This is super common for folks new to Python's random module! random.shuffle() is an in-place operation—it modifies the list you pass directly, instead of creating and returning a brand new shuffled list. That's why it always returns None.
In your code, after calling random.shuffle(c), the original list c is already shuffled. You don't need to assign the result to z—just print c directly to see the shuffled version.
Here's a fixed version of your code:
import random a = list(range(1,99)) b = list(range(1,99)) c = list(range(1,99)) print("Original c:", c) random.shuffle(a) random.shuffle(b) random.shuffle(c) # Now a, b, c are all shuffled in-place print("Shuffled c:", c)
If you don't want to modify the original list and need a new shuffled list instead, use random.sample()—it returns a new list while leaving the original untouched:
import random c = list(range(1,99)) z = random.sample(c, k=len(c)) # k specifies how many elements to take (all here) print("Original c:", c) print("New shuffled list z:", z)
Your code fails because len(x,y,z) is invalid syntax—len() only accepts one iterable as an argument, not multiple. Also, you need to make sure x, y, z are three lists of the same length (each storing the x/y/z coordinates of your points).
Here are two solid ways to implement this:
Option 1: Use zip() (recommended)
zip() packs corresponding elements from multiple lists into tuples, making it easy to iterate through each 3D point:
# First, prepare your coordinate lists (same length) x_coords = [1, 2, 3, 4] y_coords = [5, 6, 7, 8] z_coords = [9, 10, 11, 12] # Generate all 3D points and store them in a list points = [] for x, y, z in zip(x_coords, y_coords, z_coords): points.append((x, y, z)) # Or use a list comprehension for a shorter version points = [(x, y, z) for x, y, z in zip(x_coords, y_coords, z_coords)] print(points) # Output: [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Option 2: Loop with indexes
If you prefer using indexes, just grab the length of one list (make sure all three are the same length first):
x_coords = [1, 2, 3, 4] y_coords = [5, 6, 7, 8] z_coords = [9, 10, 11, 12] points = [] # Use the length of x_coords as the loop count for i in range(len(x_coords)): point = (x_coords[i], y_coords[i], z_coords[i]) points.append(point) print(points)
Quick note: Avoid creating dynamic variables like q1, q2, q3—storing all points in a list is way easier to work with later (you can loop through them, index them, etc.).
内容的提问来源于stack exchange,提问作者tgmjack

