使用 lambda 过滤列表(一行代码)

我有一个包含人名的 txt 文件。


我打开它并希望使用过滤器和 lambda 函数仅获取具有用户输入长度的名称。


问题是我得到的列表是空的[]。


names_file = open('names.txt').read().split()

user_choice = input("Enter name length: ")

print(list(filter(lambda c : len(c) == user_choice, names_file)))

问题是什么 ?


慕沐林林
浏览 87回答 2
2回答

繁星淼淼

看到这一行user_choice = input("Enter name length: ")您正在接受字符串输入。如果你想接受一个整数输入,你需要写int(input()). 我希望这能解决问题。

一只名叫tom的猫

user_choice = int(input("Enter name length: ")) 应该修复它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python