python - 如何从元组列表中获取第二项,然后将其与 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'
我有点知道这意味着什么,但我不知道如何解决它。
解决方案
你的错误
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 的解决方案做了同样的事情,只是用更少的词。
推荐阅读
- asp.net - 当值来自gridview时在Itextsharp中添加标题页
- python - python Jupyter笔记本单元格的内容是否可以在所述笔记本内运行的代码中进行操作?
- node.js - ping node js app并自动重启pm2进程的简单方法
- python - 我的 Python 课感觉非常过分。有没有更短的方法来做到这一点?
- java - org.openqa.selenium.WebDriverException:等待驱动程序服务器以 Selenium 和 Java 启动时超时
- java - 获取传递给对象的 Firebae 数据库数据
- python - Heroku 找不到 sdl-config?
- java - 使用 Firebase 在我的聊天应用程序中杂乱无章的聊天消息
- pandas - 获取 datetime 和恒定时间变量 pandas 之间的时间差
- c - 通过 UART 在 ESP32 中校正传感器值