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

时间:2019-11-02 09:34:31

标签: python list tuples

因此有一个元组列表。像这样:

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

它具有名称,人员年龄和出生年份。

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

listPeople = [p1, p2, p3]

我有功能“较早”,它要求我刚创建的列表人以及年龄的一些数字,比如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'

我知道这是什么意思,但我不知道如何解决。

2 个答案:

答案 0 :(得分:2)

您的错误

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

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

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

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

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

一旦了解了它的工作原理,就可以继续列出各种理解,以查看Aivar的解决方案仅用较少的单词即可完成相同的工作。

答案 1 :(得分:1)

列表理解不是更简单(“为列表中第二项大于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)]