首页 > 解决方案 > 使用 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)

标签: pythonlist

解决方案


您没有在第二个 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)

推荐阅读