求教怎么能比较优雅的实现这个功能

2019-04-29 18:50:05 +08:00
 warcraft1236

有一段 json,格式大概是这样的

"data":[
    {
        "file": "https://fvs.io/re.........",
        "label": "480p",
        "type": "mp4"
    },
    {
        "file": "https://fvs.io/redirector.......",
        "label": "720p",
        "type": "mp4"
    }
]

我想取出来 label 中清晰度最高的

5249 次点击
所在节点    Python
37 条回复
Foreverdxa
2019-04-30 08:32:39 +08:00
js 里的 reduce 可以实现,前面老哥都是很详细了。。。
zqx
2019-04-30 08:56:54 +08:00
js:
Math.max(arr.map((item)=>{return item.label}))
WuwuGin
2019-04-30 09:00:49 +08:00
啥排序啊,就取个最大值而已
nacosboy
2019-04-30 09:21:05 +08:00
maxResolution := 0

for _, d := range data {
if maxResolution < parseXXX(d.Label) {
maxResolution = parseXXX(d.Label)
}
}

return maxResolution
nacosboy
2019-04-30 09:22:38 +08:00
```go
func main() {
maxResolution := 0

for _, d := range data {
if maxResolution < parseXXX(d.Label) {
maxResolution = parseXXX(d.Label)
}
}

print(maxResolution)
}

```
zblongfei
2019-04-30 09:28:05 +08:00
遍历一边就能拿到手非常简单
daguaochengtang
2019-04-30 09:32:59 +08:00
@zqx 你这个表达式返回的是 NaN。 第一,Math.max 不能接收数组。第二,label 是字符串,要转成数字
Math.max(...arr.map(item => parseInt(item.label)))
Chenamy2017
2019-04-30 10:01:17 +08:00
遍历
取每个 label,转数字,比较大小;如果大的这个对象就暂存
一遍下来就能拿到暂存的最大的对象了。
dicc
2019-04-30 10:03:12 +08:00
你们都忽略了 在比较的时候 1080P < 480P 的问题..
fzzff
2019-04-30 10:05:10 +08:00
data = [
{
"file": "https://fvs.io/re.........",
"label": "480p",
"type": "mp4"
},
{
"file": "https://fvs.io/redirector.......",
"label": "1020p",
"type": "mp4"
},
{
"file": "https://fvs.io/redirector.......",
"label": "720p",
"type": "mp4"
}
]

data.sort(key=lambda d:int(d['label'][:-1]), reverse=True)
print(data[0])
dicc
2019-04-30 10:05:26 +08:00
sorted(a, key=lambda x:int(x['label'][:-1]), reverse=True)

第一个就是
inhzus
2019-04-30 10:08:21 +08:00
max(json.dumps(d)['data'], key=lambda x: int(x['label'][:-1]))
zqx
2019-04-30 10:34:13 +08:00
@nikolausliu 手机上打的,疏忽了。parseInt 可以将字符串中数字部分提取出来,而 Number 只能构造数值,最后应该用...展开数组给 max 函数
Akichu
2019-04-30 10:53:12 +08:00
用 js 的 ramda 库:
R.last(R.sortBy(R.prop('label'), data))
ccdrea
2019-04-30 10:54:30 +08:00
1.
max(data, key=lambda x: int(x['label'].replace('p','')))

2.
data.sort(key=lambda x:int(x['label'].replace('p','')))
data[-1]
ccdrea
2019-04-30 11:19:47 +08:00
补充:
from collections import OrderedDict

c = list(map(lambda x:OrderedDict(x),a))[-1]

# OrderedDict 实现一个 FIFO 得 dict
TommyLemon
2019-04-30 12:23:17 +08:00
能用 SQL 过滤最好,不能用就遍历再对比

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/559861

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX