简体   繁体   中英

Converting a list of arrays into a single list of elements in python

I would like to convert a list of arrays into a single list of elements.

I have this list of arrays:

[array([ 1.65988671]), array([ 1.66663357]), array([ 1.53351122]), array([ 1.60234953])]

and I would like to have this:

[1.6153020312169204, 1.6843892323785852, 1.662793812752394, 1.6332755497183022].

I used:

List=[]
for i in range(arr)):
    List.append(arr[i].tolist())

But I get this [[ 1.65988671]), [ 1.66663357], [ 1.53351122], [ 1.60234953]]

What's wrong with my code?

使用my_list.extend而不是my_list.append ,它应该做您想要的。

import numpy as np

arr = [
    np.array([ 1.65988671]), 
    np.array([ 1.66663357]), 
    np.array([ 1.53351122]), 
    np.array([ 1.60234953])]
    my_list = []
    for x in arr:
        my_list.append(x[0])

This works for me.

You can do this with a list comprehension:

[item for arr in list_with_arrays for item in arr.tolist()]

Also you can use hstack:

list_with_arrays = [np.array([1, 2]), np.array([2, 3]), np.array([5, 6, 7])]
np.hstack(list_with_arrays).tolist()

[1, 2, 2, 3, 5, 6, 7]

I am by no means an expert and this may not make sense nor be the best way. But it works.

The way you are going about it you are appending each list in to a new list and therefore keeping them as a list. By adding each item to a new list (concatenating) it works.

I have even added some extra data to one of the lists to ensure it works.

start = [[ 1.65988671,1.7890], [ 1.66663357], [ 1.53351122], [ 1.60234953]]
target=[]
for i in range(len(start)):
        target = target+start[i]
print (target)

Assuming you use array from the array module in python's standard library

from array import array
arr = [array('f', [ 1.65988671]), array('f', [ 1.66663357]), array('f', [ 1.53351122]), array('f', [ 1.60234953])]
lst = [ae for el in arr for ae in el]

produces

[1.6598867177963257, 1.6666336059570312, 1.5335111618041992, 1.6023495197296143]

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