【问题标题】:Filtering a list using lambda (one line code)使用 lambda 过滤列表(一行代码)
【发布时间】:2020-07-20 13:40:44
【问题描述】:

我有一个包含人名的 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)))

有什么问题?

【问题讨论】:

  • type(user_choice) == strtype(len(c)) == int 所以它们永远不相等。
  • input 返回一个字符串,所以如果用户输入5user_choice 将是"5"。整数和字符串之间的等价性总是False
  • names_file 列表中的数据是什么样的?
  • @TadhgMcDonald-Jensen 谢谢,解决了问题!
  • 感谢大家的回答!

标签: python python-3.x list lambda filter


【解决方案1】:

看到这一行

user_choice = input("Enter name length: ")

您正在接受字符串输入。如果你想输入一个整数,你需要写int(input())。我希望这能解决问题。

【讨论】:

    【解决方案2】:

    user_choice = int(input("Enter name length: ")) 应该修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多