Python数组操作,pi*[n+1]^2 pi*[n]^2

2024-10-01 09:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个脚本,用多个圆柱体的外圆柱体减去内圆柱体。你知道吗

例如:x = pi*[n+1]**2 - pi*[n]**2

但是,我不知道如何让n在示例1-4中每次都发生更改,我希望能够更改n并让代码在新值中运行,而不必更改所有内容。你知道吗

x = pi*[1]**2 - pi*[0]**2    
x = pi*[2]**2 - pi*[1]**2
x = pi*[3]**2 - pi*[2]**2
x = pi*[4]**2 - pi*[3]**2

我试图让while循环工作,但是如果没有明确说明数组中我要引用的数字,我就不知道如何引用n。你知道吗

任何帮助都将不胜感激。你知道吗

rs = 0.2                                # Radius of first cylinder  
rc = 0.4                                # Radius of each cylinder (concrete) 
rg = 1                                  # Radius of each cylinder (soil)
BW = 3                                  # No. cylinders (concrete)
BG = 2                                  # No. cylinders (soil)
v1 = np.linspace(rs, rc, num=BW)        # Cylinders (concrete)
v2 = np.linspace(rc * 1.5, rg, num=BG)  # Cylinders (soil)

n = np.concatenate((v1, v2))            # Combined cylinders

for i in range(BW + BG):
    x = np.pi * (n[i + 1] ** 2) - np.pi * (n[i] ** 2)

Tags: ofnppirgbgrceachbw
3条回答

试试这个:

for n in range(4): # 0 to 3
    x = pi*[n+1]**2 - pi*[n]**2 #[1] - [0], [2] - [1] and so on...
    # doSomething

如果[n]是名为num的数组的索引,请将[n]替换为 num[n]就像这样:

for n in range(4): # 0 to 3
    x = pi*(num[n+1]**2) - pi*(num[n]**2) #[1] - [0], [2] - [1] and so on...
    # doSomething

如果只是n,则用n替换[n],如下所示:

for n in range(4): # 0 to 3
    x = pi*((n+1)**2) - pi*(n**2) #[1] - [0], [2] - [1] and so on...
    # doSomething

这个怎么样:

for i, value in enumerate(n[:-1]):
    print(np.pi * (n[i + 1] ** 2) - np.pi * (value ** 2))

对我来说,它印着:

0.157079632679
0.219911485751
0.628318530718
2.0106192983

也许你想要这个:

>>> values = [np.pi * (n[i + 1] ** 2) - np.pi * (value ** 2)
                          for i, value in enumerate(n[:-1])]
>>> values
[0.15707963267948971, 0.2199114857512855, 0.62831853071795885, 2.0106192982974673]

让我们来解释一下:

  • 我们必须获取列表中除最后一个元素以外的所有元素,因为n[i + 1]对最后一项失败,所以我们使用n[0:-1](如果切片的开头为0,则允许省略它;如果切片的结尾等于或大于len(n),则允许省略它)。你知道吗
  • enumerate(a_list)返回类似于表
    [(0, a_list[0]), (1, a_list[1]), ..., (n, a_list[n)]
  • for i, value in ...将每一对解压成名为ivalue的变量
  • [something for something in a_list]返回一个新列表。您可以进行计算,并过滤这些值。例如,如果您想要一个偶数整数的平方的列表小于10:
    >>> [x * x for x in range(10) if x % 2 == 1]
    [1, 9, 25, 49, 81]

由于您的数字位于numpy数组中,因此在整个数组(或数组片段)中使用广播操作要比编写显式循环并对单个项进行操作有效得多。这是使用numpy的主要原因!你知道吗

尝试以下操作:

# compute your `n` array as before

areas = pi * n**2   # this will be a new array with the area of each cylinder
area_differences = areas[1:] - areas[:-1]   # differences in area between adjacent cylinders

相关问题 更多 >