嵌套列表比较值

时间:2019-07-24 07:04:33

标签: python python-3.x

假设我有以下(字符串)嵌套列表

struct AreaData: Decodable {
    let iD : String?
    let name : String?
    let parentId : String?
    let sublevel : [AreaData]?
    let on : String?
    let off : String?

    enum CodingKeys: String, CodingKey {
        case iD = "ID"
        case name = "Name"
        case on = "On"
        case off = "Off"
        case parentId, sublevel
    }
}
  1. 我想将每个子列表中的第4个元素与其他元素进行比较: 例如:我想比较186,2093..573并打印每个元素的最大值。
  2. 我要打印第四个元素最高的子列表的第二个元素。

3 个答案:

答案 0 :(得分:1)

data = [['78130 00821', '98453 94494', '01-09-2016 06:01:12', '186'],
['78298 91466', '(022)28952819', '01-09-2016 06:01:59', '2093'],
['97424 22395', '(022)47410783', '01-09-2016 06:03:51', '1975'],
['93427 40118', '(080)33118033', '01-09-2016 06:11:23', '1156'],
['90087 42537', '(080)35121497', '01-09-2016 06:17:26', '573']]


print (max(data, key=lambda x: int(x[3]))[1])

输出:

(022)28952819

具有基本的for循环:

max = 0
for item in data:
    if int(item[3]) > max:
        max = int(item[3])
        result = item[1]

print (result)

输出:

(022)28952819

答案 1 :(得分:0)

您可以将maxkey一起使用,以指示它应使用第四个元素

>>> l = [['78130 00821', '98453 94494', '01-09-2016 06:01:12', '186'],    
... ['78298 91466', '(022)28952819', '01-09-2016 06:01:59', '2093'],    
... ['97424 22395', '(022)47410783', '01-09-2016 06:03:51', '1975'],    
... ['93427 40118', '(080)33118033', '01-09-2016 06:11:23', '1156'],    
... ['90087 42537', '(080)35121497', '01-09-2016 06:17:26', '573']]
>>> 
>>> max(l, key=lambda sl: int(sl[3]))
['78298 91466', '(022)28952819', '01-09-2016 06:01:59', '2093']
>>> max(l, key=lambda sl: int(sl[3]))[1]
'(022)28952819'

答案 2 :(得分:0)

data = [['78130 00821', '98453 94494', '01-09-2016 06:01:12', '186'],    
['78298 91466', '(022)28952819', '01-09-2016 06:01:59', '2093'],    
['97424 22395', '(022)47410783', '01-09-2016 06:03:51', '1975'],    
['93427 40118', '(080)33118033', '01-09-2016 06:11:23', '1156'],    
['90087 42537', '(080)35121497', '01-09-2016 06:17:26', '573']]

result = max(data, key=lambda x: int(x[3]))[1]

结果:

'(022)28952819'