Python 使用if语句在嵌套列表中搜索
我试图从值低于50的嵌套列表中取出元素,并用相应的值显示它们。我试着做了,但什么也做不到 代码如下:Python 使用if语句在嵌套列表中搜索,python,list,Python,List,我试图从值低于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[
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循环中迭代变量“row”。变量“row”的作用域以第一个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)
您不需要
deptInfo
只要这样做:
belowFifty = []
for row in range(len(deptNums)):
if (50 > deptNums[row]):
belowFifty.append([newList[row],deptNums[row]])
belowFifty
输出:
[['payroll', 10], ['accounting', 20], ['security', 30], ['office', 40]]
一种使用列表理解而不是传统循环的速记方法。
这就是你想要的吗?此示例使用函数和
基本上,zip
函数将两个列表对齐并一起迭代-因此,在这里,我们可以将您的部门名称和部门编号放在一起,将它们成对迭代
newList = ["payroll", "accounting", "security", "office", "sales"]
# I edited this to match the length of your department names.
deptNums = [10 * index for index in range(1, len(newList))]
# Use list comprehension to iterate, test and create a new list all in ONE line.
deptInfo = [[num, dpt] for num, dpt in zip(newList, deptNums) if dpt < 50]
有两个问题:
1.您正在将deptInfo
初始化为[[]]
,因此在附录之后您会得到:
[[],
['payroll', 10],
['accounting', 20],
['security', 30],
['office', 40],
['sales', 50]]
deptInfo
中的项目,但尝试使用索引(row
)检查deptNum
,该索引是上一个迭代变量,当前的值为5
,deptNum[5]
的值为60
,因此您的if
不会检查任何内容。这是您的固定代码:newList = ["payroll", "accounting", "security", "office", "sales"]
deptNums = [10 * index for index in range(1, 16)]
print([[i,j] for i,j in zip(newList, deptNums) if j < 50])
newList=[“工资单”、“会计”、“证券”、“办公室”、“销售”]
deptNums=[10*范围内索引的索引(1,16)]
打印([[i,j]代表zip中的i,j(新列表,部门),如果j<50])
我不理解你的第二个循环:迭代变量items
没有使用?你也在使用行
变量,它是上一个循环中剩下的4
,因为deptNums[4]==50
,所以if
语句对于任何迭代都不是真的。我试着把deptNums[items]放在第一位,但它给了我一个错误,“列表索引必须是整数或切片,而不是列表”
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 > items[1]):
belowFifty.append(items)
print(belowFifty)
newList = ["payroll", "accounting", "security", "office", "sales"]
deptNums = [10 * index for index in range(1, 16)]
print([[i,j] for i,j in zip(newList, deptNums) if j < 50])