基于islice和cycle多层处理双列表,生成自定义序列输出需求
Solution to Generate the Desired Sequence
First, let's break down the pattern we can see in your sample output:
For each number x in Numberset1:
- We use a starting
yvalue tied tox:start_y = x - 9(so 10 maps to 1, 11 maps to 2, 12 maps to 3) - We iterate over
yvalues in a cyclic permutation ofNumberset2starting atstart_y(e.g., starting at 2 gives [2,3,4,5,1]) - For each
y, we then iterate overzvalues in another cyclic permutation ofNumberset2starting aty(e.g., starting at 2 gives [2,3,4,5,1]) - Each triplet (x, y, z) is added to the output sequence in order.
Here's the Python code that implements this logic perfectly:
Numberset1 = [10, 11, 12] Numberset2 = [1, 2, 3, 4, 5] def get_cyclic_sequence(lst, start_value): """Generate a cyclic permutation of the list starting at the given value""" idx = lst.index(start_value) return lst[idx:] + lst[:idx] output_elements = [] for x in Numberset1: # Determine the starting y for the current x start_y = x - 9 # Get the cyclic sequence of y values starting at start_y y_sequence = get_cyclic_sequence(Numberset2, start_y) for y in y_sequence: # Get the cyclic sequence of z values starting at y z_sequence = get_cyclic_sequence(Numberset2, y) for z in z_sequence: # Add each triplet's elements to our output list output_elements.extend([str(x), str(y), str(z)]) # Join all elements into a single space-separated string final_output = ' '.join(output_elements) print(final_output)
How this works:
- The
get_cyclic_sequencefunction takes a list and a starting value, then returns the list rotated so it begins at that value (e.g., input [1,2,3,4,5] and start 3 returns [3,4,5,1,2]) - We loop through each
xinNumberset1, calculate the startingy, then generate the cyclic y sequence - For each
y, we generate the cyclic z sequence, then add each (x,y,z) triplet as strings to our output list - Finally, we join all elements with spaces to produce the exact sequence you requested.
内容的提问来源于stack exchange,提问作者Python_newbie
相关产品推荐
相关产品推荐

