如何从元组列表中获取第二项,然后将其与python中给定的数字进行比较

2024-09-30 20:21:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我把它们放在一个新的列表里:

listPeople = [p1, p2, p3]

我有一个函数,要求列出我刚列出的人和一些年龄数字,比如说15:

olderPerson = Older(listPeople, 15)

我不知道如何将给定的15岁与列表中的人进行比较,并只返回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'

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


Tags: 列表ageifp2年龄p3p1lis
2条回答

Isin NOT list(“为列表中第二项大于15的每条记录提供记录”):

>>> lst = [("Name1", 14, 2005), ("Name2", 21, 1998), ("Name3", 18, 2001)]       
>>> [record for record in lst if record[1] > 15] 
[('Name2', 21, 1998), ('Name3', 18, 2001)]

你的错误

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

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

Aivar的回答显示了一种更“Pythonic”的方法,即使用一种非常适合Python语言的方法。他使用的“列表理解”将以每条记录为例,其中一条记录为例(“Name1”,14,2005),并且只保留第二个元素大于15的记录(记录[1]是第二个元素)。其余记录将自动加入新列表

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

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

一旦你理解了这是如何工作的,你就可以继续列出理解,看看Aivar的解决方案做同样的事情,只需要更少的单词

相关问题 更多 >