list 是由数字组成,数字可能有重复。比如
[-10, -1.67, 1.74, 27.43, -3.4, -0.59, 13.01, 18.69, 0.68, -1.17, 2.96, 13.14, 12.76, -0.14, 12.76, 3, 3, 5, 7, -2, 20]
现在要求是传入参数 n,然后将 list 按照最大最小值分成 n 份,然后统计每份中的元素有多少个
比如 n=5,那就分成
-10 到 -4
-4 到 2
2 到 8
8 到 14
14 到 20
然后统计这个范围内的元素个数
请问怎么用最少的 for 循环来实现呢?
1
NerdTsai 2019-11-15 13:45:55 +08:00
除去内置方法中的 for 循环实现,,大概只需要 1 个 for 吧
|
2
hakono 2019-11-15 13:53:53 +08:00 via iPhone
数组先排个序,然后一个 for 循环遍历一遍不就行了。。。
|
3
foamvalue 2019-11-15 13:54:15 +08:00
已知最大最小值的情况下么,只要一个 for。
|
4
fengmumu 2019-11-15 13:56:55 +08:00
只能想到 先遍历一遍 获取最大最小数值,然后得出区间,再遍历一遍 归类放,循环两次
|
5
wangyzj 2019-11-15 14:07:41 +08:00
```
newlist = [] templist = [] num = len(mylist) // N j = 0 for i in sorted(mylist): if j % num == 0 and j != 0: newlist.append(templist) templist = [] if j % num < num: templist.append(i) j = j + 1 print(newlist) ``` |
6
alphatoad 2019-11-15 14:11:41 +08:00 via iPhone
O(n)
|
7
cherbim 2019-11-15 14:24:08 +08:00 via iPhone
先用 sorted 排序,然后一个 for 遍历……
|
8
arloor 2019-11-15 15:09:38 +08:00 via Android
java stream 可以做到不写 for
|
9
xiaolinjia 2019-11-15 16:29:31 +08:00
import math
a = [-10, -1.67, 1.74, 27.43, -3.4, -0.59, 13.01, 18.69, 0.68, -1.17, 2.96, 13.14, 12.76, -0.14, 12.76, 3, 3, 5, 7, -2, 20] def function(temp: list, n): step = math.ceil(len(temp)/n) temp.sort() s = slice(0, step) for i in range(n): print(temp[s]) s = slice(s.start + step, s.stop + step) if __name__ == '__main__': function(a, 6) |
10
TimePPT 2019-11-15 21:54:41 +08:00 3
# 如果用 pandas 可以一个 for 都不用
import pandas as pd lst = [-10, -1.67, 1.74, 27.43, -3.4, -0.59, 13.01, 18.69, 0.68, -1.17, 2.96, 13.14, 12.76, -0.14, 12.76, 3, 3, 5, 7, -2, 20] n = 5 df_cut = pd.cut(lst, n) df_cut.value_counts() # pandas.cut 可以设置一系列函数确定均分区间的规则: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.cut.html |
11
ladypxy OP |
12
ladypxy OP @wangyzj 这个写法只是把 list 的元素按照 N 来分成新的列表。而不是根据最大最小值来计算区间然后分配。而且还会把最大值忽略。。
|
13
wangyzj 2019-11-18 00:51:15 +08:00
@ladypxy 完,理解错你的意思了
你要的是这个意思? mylist = sorted(mylist) newlist = [] templist = [] min = mylist[0] max = mylist[len(mylist)-1] delta = (max-min) / N next = min + delta j = 0 for i in mylist: if i <= next: templist.append(i) if i >= next: newlist.append(templist) next = next+delta templist = [] templist.append(i) j += 1 if j == len(mylist): newlist.append(templist) print(newlist) |
14
wangyzj 2019-11-18 00:56:16 +08:00
@ladypxy 完,理解错你的意思了
你要的是这个意思? mylist = sorted(mylist) newlist = [] templist = [] min = mylist[0] max = mylist[len(mylist)-1] delta = (max-min) / (N-1) next = min + delta j = 0 for i in mylist: if i <= next: templist.append(i) if i >= next: newlist.append(templist) next = next+delta templist = [] templist.append(i) j += 1 if j == len(mylist): newlist.append(templist) print(newlist) |