python - 使用 if 语句搜索嵌套列表
问题描述
我试图从嵌套列表中取出值低于 50 的元素以及与它们对应的值以显示它们。我试着做,但它什么也没给我。
这是代码:
newList = ["payroll", "accounting", "security", "office", "sales"]
deptNums = [10 * index for index in range(1, 16)]
deptInfo = [[]]
for row in range(0, len(newList)) :
deptInfo.append([newList[row], deptNums[row]])
print(deptInfo)
belowFifty = []
for items in deptInfo:
if (50 > deptNums[row]):
belowFifty.append(newList[row],deptNums[row])
print(belowFifty)
解决方案
您没有在第二个 for 循环中迭代变量“行”。变量“行”的范围以第一个 for 循环结束。更合适的代码:
newList = ["payroll", "accounting", "security", "office", "sales"]
deptNums = [10 * index for index in range(1, 16)]
deptInfo = [[]]
for row in range(0, len(newList)) :
deptInfo.append([newList[row], deptNums[row]])
print(deptInfo)
belowFifty = []
for item, number in zip(newList, deptNums):
if 50 > number:
belowFifty.append([item, number])
print(belowFifty)
推荐阅读
- sql-server - 带有 SOUNDEX 的 PATINDEX
- android - DownloadManager 排队队列文件,并在 Oreo 及以上版本中继续下载
- node.js - 无法将 NPM 包安装在范围内或依赖范围内(或者看起来像那样)
- laravel - 拉拉维尔 | 以随机顺序选择测验问题并显示每个问题的答案
- jquery - 如何将序列号输入到 jTable 中的字段中?
- javascript - 单击表中的特定按钮
- oracle - 创建过程并在表中插入值
- android - Android Studio - 用户登录
- angularjs - 尝试在 Web API 和 Angular 中将数据表导出到 Excel(1.000.000 条记录),编写流式处理会引发内存不足异常
- amazon-web-services - 如何使用 boto3 删除 VPC 及其所有依赖项?