给定一维ndarray和一个整数,生成此ndarray的最有效方法是什么?

时间:2019-11-03 00:41:53

标签: python numpy multidimensional-array

给出arrayn会生成x

输入

array = [1 8 38 17]
n = 2

x = [1 2 3 8 9 10 38 39 40 17 18 19]

2 个答案:

答案 0 :(得分:2)

如果数组和n都很小,则Patol75给出的代码很快(尽管必须更改为适用于n的任何值)。

def f(array,n):
    return sum([[x + i for i in range(n+1)] for x in array],[])

当数组和n都很大时,速度很慢。在这种情况下,这是我最好的镜头。

def g(array,n):
    temp = np.vstack([array+i for i in range(n+1)])
    return np.hstack([temp[:,i] for i in range(len(array))])

这是时间。

小尺寸。

array = np.array([1, 8, 38, 17])
n = 2

%timeit f(array,n)
9.44 µs ± 547 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit g(array,n)
23.4 µs ± 1.65 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

更大的尺寸。

array = np.random.randint(0,1000,1000)
n = 100

%timeit f(array,n)
479 ms ± 46.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit g(array,n)
2.69 ms ± 62.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

答案 1 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout   xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:background="@color/white"
          android:orientation="vertical"
          android:weightSum="100"
          tools:context="cz.johngalt.app.MainActivity">

        <!-- here's the toolbar -->
        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="10" />

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white">
                
                <!-- here goes the rest of your xml -->
        
        <ScrollView/>            

      <LinearLayout/>

    <android.support.v4.widget.DrawerLayout/>