一个很简单的算法题可就是不知道怎么写
就是把一个列表里的连续的负数提取出来组成一个新列表存在一个大列表里a =
就是结果输出成这样:
[[-4.3, -4.12, -8.91], [-12.0], [-14.0], [-15.69, -5.08], [-11.11], [-17.86, -24.24, -17.07, -6.25, -5.88, -5.56], [-25.45], [-14.49], [-6.58, -3.7, -1.19], [-36.0], [-5.88], [-8.57], [-5.33], [-3.95, -2.53, -4.94, -2.35], [-1.16]...........................................]
就是相邻的负数就存在子列表里, 也包括只有一个负数的时候, 一遇到正数或者0就断开, 后面再遇到负数就再存到一个新的子列表里, 有没有一个看上去不是太复杂效率又比较高的写法, 请各位大神大佬教教我 本帖最后由 jackz007 于 2022-9-2 17:41 编辑
a =
d , i , k = [] , 0 , 0
for x in a:
if x < 0:
if not k:
d . append([])
d . append(x)
k += 1
else:
if k:
i += 1
k = 0
print(d)
运行实况:
D:\\Python>python x.py
[[-4.3, -4.12, -8.91], [-12.0], [-14.0], [-15.69, -5.08], [-11.11], [-17.86, -24.24, -17.07, -6.25, -5.88, -5.56], [-25.45], [-14.49], [-6.58, -3.7, -1.19], [-36.0], [-5.88], [-8.57], [-5.33], [-3.95, -2.53, -4.94, -2.35], [-1.16], [-18.52], [-1.61], [-11.43], [-11.02, -4.95, -5.21], [-4.4, -8.62], [-2.75, -6.92, -4.73, -5.67, -21.43], [-10.38, -3.68, -9.29], [-10.33, -4.85, -10.83], [-3.52], [-25.73], [-7.58, -6.69, -11.73, -16.24], [-1.61], [-7.75], [-6.05, -6.44], [-10.73], [-10.45], [-6.77], [-9.16, -16.23, -15.18], [-5.26, -16.11, -29.14, -8.41], [-6.82], [-17.52, -10.88, -12.21, -27.15], [-6.47], [-22.84, -9.6, -6.19, -24.53,-32.5], [-28.81], [-28.26, -18.18], [-45.45, -10.0, -44.44, -86.67], [-266.67],[-100.0], [-200.0, -16.67], [-52.38], [-43.66, -55.0], [-0.6, -1.21], [-28.08],[-16.03, -0.52, -17.9], [-18.13, -29.76], [-3.75, -35.28, -42.86], [-36.26], [-13.13], [-13.93, -18.55], [-9.73], [-14.34, -4.75, -4.28], [-3.94, -4.3], [-3.77, -6.32], [-10.65], [-10.68], [-7.13, -4.56, -0.5, -8.33, -10.47], [-3.95], [-15.18, -8.78], [-28.76, -5.05], [-2.71, -12.07, -8.63, -2.89, -4.17], [-7.05, -1.21], [-13.73], [-9.04, -5.62, -16.58, -11.86, -5.98], [-18.86, -5.18], [-0.65, -0.26], [-4.98], [-5.3], [-3.68, -2.22], [-1.64], [-0.64], [-15.22, -10.32, -0.5, -6.74, -11.76], [-1.36, -5.42, -10.22], [-12.77], [-6.21], [-5.75, -6.98, -12.26], [-5.34, -1.59], [-2.07], [-7.54], [-6.59, -22.02], [-10.69, -5.58, -4.0, -0.51, -2.38, -0.4, -7.69], [-14.03]]
D:\\Python> a =
res, r = [], []
for i in a:
flg = True if i < 0 else False
if not flg:
if r:
res.append(r)
r = []
else:
r.append(i)
else:
if r:
res.append(r)
print(res) a =
arr, temp = list(), list()
for num in a:
if num >= 0 and temp:
arr.append(temp)
temp = list()
else:
temp.append(num)
print(arr) qq1151985918 发表于 2022-9-2 17:41
感谢大佬指教{:5_106:}{:5_106:}, 已认真学习 jackz007 发表于 2022-9-2 17:38
运行实况:
多谢大佬指教{:5_106:}, 已认真学习
页:
[1]