【问题标题】:Python: Removing a range of numbers from array listPython:从数组列表中删除一系列数字
【发布时间】:2013-10-21 08:51:51
【问题描述】:

我在从数组列表中删除 a 到 b 范围内的元素时遇到问题。我在网上搜索的解决方案似乎只适用于单个元素、相邻元素和/或整数元素。我处理浮点数。

self.genx = np.arange(0, 5, 0.1)

temp_select = self.genx[1:3] #I want to remove numbers from 1 - 3 from genx
print(temp_select)
self.genx = list(set(self.genx)-set(temp_select))
print(self.genx)
plt.plot(self.genx,self.geny)

但是我在控制台中得到以下信息,这是因为我减去浮点数而不是整数,所以它实际上是减去而不是删除,如果处理整数,它会做什么:

genx: [ 0.0 , 0.1 , 0.2 , 0.3 , 0.4 , 0.5 , 0.6 , 0.7 , 0.8 , 0.9 , 1.0, 1.1 , 1.2 , 1.3 , 1.4 , 1.5 , 1.6 , 1.7 , 1.8 , 1.9 , , 2.2 , 2.3 , 2.4 , 2.5 , 2.6 , 2.7 , 2.8 , 2.9 , 3.0 , 3.1 , 3.2 , 3.3 , 3.4 , 3.5 , 3.6 , 3.7 , 3.8 , 3.9 , 4.0 , 4.1 , 4.2 , 4.3 , 4.4 , 4.5 , 4.6 , 4.7 , 4.8 , 4.9]

temp_select:[0.1 0.2]

GENX(减去后):[0.0,0.5,2.0,3.0,4.0,1.5,1.0,1.1000000000000001,0.70000000000000007,0.90000000000000002,2.7000000000000002,0.30000000000000004,2.9000000000000004,1.9000000000000001,3.3000000000000003,0.40000000000000002,4.7000000000000002,3.4000000000000004,2.2000000000000002,2.8000000000000003, 1.4000000000000001,0.60000000000000009,3.6000000000000001,1.3,1.2000000000000002,4.2999999999999998,4.2000000000000002,4.9000000000000004,3.9000000000000004,3.8000000000000003,2.3000000000000003,4.8000000000000007,3.2000000000000002,1.7000000000000002,2.5,3.5,1.8,4.1000000000000005,2.4000000000000004,4.4000000000000004,1.6000000000000001,0.80000000000000004,2.6000000000000001,4.6000000000000005,2.1000000000000001, 3.1000000000000001, 3.7000000000000002, 4.5]

【问题讨论】:

  • 请注意,方括号 [] 用于基于 index 的访问。 self.genx[1:3] 表示“self.genx 的第一个和第二个元素”。这与这些索引处的 value 存储完全无关。

标签: python arrays matplotlib range


【解决方案1】:

我没有对此进行测试,但您应该可以执行以下操作:

self.genx = [ item for item in self.genx if not range_min < item < range_max ]

【讨论】:

  • 这很好用!但是,它会将数字四舍五入。所以,如果我设定最低= 2,最大值= 4,GENX是:[0.0,0.10000000000000001,0.20000000000000001,0.30000000000000004,0.40000000000000002,0.5%,0.60000000000000009,0.70000000000000007,0.80000000000000004,0.90000000000000002,1.0,1.1000000000000001,1.2000000000000002,1.3,1.4000000000000001,1.5,1.6000000000000001, 1.7000000000000002,1.8,1.9000000000000001,2.0,4.0,4.1000000000000005,4.2000000000000002,4.2999999999999998,4.4000000000000004,4.5 4.6000000000000005,4.7000000000000002,4.8000000000000007,4.9000000000000004]可定影跨度>
【解决方案2】:
self.genx = [ item for item in self.genx if not range_min <= item <= range_max ]

这是你想要的吗??

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 2014-01-24
    • 2013-09-20
    • 1970-01-01
    • 2013-10-27
    • 2017-05-07
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    相关资源
    最近更新 更多