简体   繁体   中英

storing values from loop

For example I have this code:

for r in res:
    for x,y in r:
        print(x,y)

And the output is this:

[0 0 0 1 0 0 0 0 0 1 1 0 1] (0.3779644730092272, 1)
[1 1 0 0 1 1 0 0 0 0 0 0 0] (0.4472135954999579, 0)
[0 0 1 1 0 0 0 1 0 0 0 0 1] (0.4472135954999579, 1)

But how do I store the first column which is the 0's and 1's in a single variable like this:

[[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]]

I also tried this:

for r in res:
    for x,y in r:
        first = x

But this only stores the last value. Is there a neat way or a one liner in python that can do this?

That looks like a straight list comprehension:

result = [x for r in res for x,y in r]

You seem to be working with 2D arrays of numbers - you might consider using numpy here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM