Fraz - 1 year ago 78

Python Question

I am wondering if there is a better way to vectorize the following:

`array = []`

for ele in long_list:

if condition:

array.append(1)

vector = np.array(array)

Now this is essentially

`np.ones(len(long_list))`

`if`

Is there a better (vectorized) way of achieving the above?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
vector = np.fromiter((1 for ele in long_list if condition), dtype=int)
```

This should be faster than either:

```
vector = np.ones(len([x for x in long_list if conditon]))
```

or

```
vector = np.array( [1 for ele in long_list if condition(ele)] )
```

because it avoids building the filtered list, due to the fact that `(1 for ele in long_list if condition)`

returns a generator not a list.

**EDIT**

I'm wondering if this isn't also a viable option:

```
vector = np.array( (1 for ele in long_list if condition(ele)) )
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**