首页 > 解决方案 > 如何从元组列表中获取第二项,然后将其与 python shell 中的给定数字进行比较

问题描述

所以有一个元组列表。像这样:

p1 = ("Name1", 14, 2005)
p2 = ("Name2", 21, 1998)
p3 = ("Name3", 18, 2001) 

它有一个名字,人的年龄和他们出生的年份。

我将它们像这样放在一个新列表中:

listPeople = [p1, p2, p3]

我有函数 Older 要求我刚刚创建的 listPeople 和一些年龄数字,比如说 15:

olderPerson = Older(listPeople, 15)

我不知道应该如何将给定的 15 岁与 listPeople 进行比较,并只返回 15 岁以上的人。像这样:

[('Name2', 18, 2001), ('Name3', 21, 1998)]

现在我有这个:

def Older(listOfPeople, age):
    newList = []
    ageInList = [lis[1] for lis in listOfPeople] #gives me all the age numbers

    if age > ageInList :
        newList.append(listOfPeople)
    return newList

我不断收到此错误

if height > heightInList:
TypeError: '>' not supported between instances of 'int' and 'list'

我有点知道这意味着什么,但我不知道如何解决它。

标签: pythonlisttuples

解决方案


你的错误

TypeError: '>' not supported between instances of 'int' and 'list'

来自年龄是一个数字,ageInList 是一个列表(所有年龄的列表)。

Aivar 的回答显示了一种更“Pythonic”的方式,即使用一种非常适合 Python 语言的方式。他使用的“列表推导”将获取每条记录,其中一条记录例如(“Name1”,14,2005),并且只保留第二个元素在15以上的记录(record[1]是第二个元素) . 剩余的记录会自动加入到一个新列表中。

对于学习体验,您的功能可以这样更改:

def Older(listOfPeople, age):
    newList = []
    for record in listOfPeople:
        if record[1] > age:
            newList.append(record)
    return newList

一旦你理解了它是如何工作的,你就可以继续列出推导式,看看 Aivar 的解决方案做了同样的事情,只是用更少的词。


推荐阅读