簡體   English   中英

提取所有大於 'm' 且小於 'n' 的列表元素

[英]Extract all the list elements that are greater than 'm' and less than 'n'

這是查找所有大於m且小於n的列表元素的代碼。

注意: mn是作為輸入提供的 integer 值

樣本輸入:

[ 1, 5, 9, 12, 15, 7, 12, 9 ] (array)

6 (m)

12 (n)

樣品 output:

[ 9 7 9 ]

這是我的代碼:

import ast 

input_list=ast.literal_eval(input())

m=int(input())

n=int(input())

import numpy as np

array_1 = np.array(input_list)

final_array =array_1[array_1>m array_1<n]

print(final_array)

如果numpy是強制性的,那么您可以這樣做:

import ast 
import numpy as np

input_list=ast.literal_eval(input())

m=int(input())

n=int(input())


array_1 = np.array(input_list)

final_array =array_1[(array_1>m)&(array_1<n)]

print(final_array)

老實說,這似乎是我在為你做作業,但無論如何,試試這個:

import ast 

input_list= ast.literal_eval(input())
m=int(input())
n=int(input())

output_list = [x for x in input_list if m<x<n]
print(output_list)

它使用列表迭代來檢查每個項目的條件。

使用&運算符

import numpy as np
import ast
input_list=ast.literal_eval(input())
m=int(input())
n=int(input())
array_1 = np.array(input_list)
final_array  = array_1[(array_1 > m) & (array_1 < n)]
print(final_array)

第 1 步:知道您可以將 arrays 與其他 arrays 索引。

x = np.arange(50) * 2
indexing_array = np.array([3, 5, 9])
print(x[indexing_array])

Step 2: Know that you can index arrays with boolean arrays, and that you can create boolean arrays by specifying conditions with an array as one of the arguments.

x = np.arange(50)
# A boolean array
print(x > 5)
# Index x with a boolean array
print(x[x > 5])

第 3 步:創建條件以使 boolean 數組准確索引原始數組中您想要的內容。

x = np.arange(50)
m, n = 5, 20
print(x[(m < x) & (x < n)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM