我在以下程序中将'mapped_list'清空,而未清除它。请解释

时间:2019-03-09 09:34:31

标签: python

numbers = {}

#assign values to the dictionary 'numbers'

for i in range(5):
 numbers[i**2] = i

#function to check if number is in 'numbers' dictionary
def check(x):
 if x in numbers:
  return True
 else:
  return False

#list with random numbers
rand_nums = [8,9,25,16,18]
filtered_list = filter(check,rand_nums)

#printing 'filtered_list'

# NOTE:- using list() constructor for printing filter object
print(list(filtered_list))


#function to add 1




def add(x):
 return x+1

mapped_list = map(add,filtered_list)

#printing 'mapped_list'

# NOTE:- using list() constructor for printing filter object
print(list(mapped_list))

2 个答案:

答案 0 :(得分:0)

不知道为什么会得到空的映射列表。

我已经尝试过您的代码(经过一些清理)

numbers = {}

for i in range(5):
    numbers[i ** 2] = i


def check(x):
    return x in numbers


rand_nums = [8, 9, 25, 16, 18]
filtered_list = list(filter(check, rand_nums))
print('filtered list: {}'.format(filtered_list))


def add(x):
    return x + 1


mapped_list = list(map(add, filtered_list))
print('mapped list: {}'.format((mapped_list)))

输出(python 3.6.3)

filtered list: [9, 16]
mapped list: [10, 17]

答案 1 :(得分:0)

filter函数总是返回可迭代的对象(就像生成器一样)。当您的代码print(list(filtered_list))被执行时,filtered_list的值将为空。因此,稍后当您通过运行以下代码映射相同的空过滤列表时:  mapped_list = map(add,filtered_list)映射函数获取空列表。

按如下所示更改您的代码: filtered_list = list(filter(check,rand_nums))达到预期的结果。