如何在Python循环中存储二进制序列集合至单一变量?
Got it, let's sort this out for you! The issue with your original code is that you're overwriting the first variable every time the loop runs, which is why only the last value sticks around. To collect all those binary sequences into a single 2D array, you need to initialize an empty list and append each sequence to it as you iterate.
Step-by-Step Solution
First, create an empty list to hold all your binary sequences. Then, modify your loop to add each sequence to this list instead of overwriting a single variable:
# Initialize an empty list to store all binary sequences binary_sequences = [] for r in res: for x, y in r: # Append each binary sequence to the list # If x is a numpy array (like your output shows), convert it to a Python list with tolist() binary_sequences.append(x.tolist()) # If x is already a standard Python list, just use: binary_sequences.append(x)
What This Does
binary_sequencesstarts empty, and each time we loop through a pair(x, y), we add the binary sequencexto the end of the list.- The
tolist()method is included because your output shows sequences like[0 0 0 1...]—this looks like a numpy array (elements separated by spaces instead of commas). Converting it to a Python list ensures you get a standard 2D list structure.
Result
After running this code, binary_sequences will be exactly the 2D array you want:
[[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1], [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1]]
If you need to keep the sequences as numpy arrays instead of Python lists, just remove the .tolist() call—you'll end up with a list of numpy arrays, which acts like a 2D array for most use cases.
内容的提问来源于stack exchange,提问作者xx4xx4

