【问题标题】:Using list comprehension as condition for if else statement使用列表推导作为 if else 语句的条件
【发布时间】:2021-11-27 20:37:08
【问题描述】:

我有以下运行良好的代码

list = ["age", "test=53345", "anotherentry", "abc"]

val = [s for s in list if "test" in s]
if val != " ":
    print(val)

但我想要做的是使用列表推导作为 if else 语句的条件,因为我需要证明多个单词的出现。知道它不起作用,我正在寻找这样的东西:

PSEUDOCODE
if (is True = [s for s in list if "test" in s])
print(s)
elif (is True = [l for l in list if "anotherentry" in l])
print(l)
else:
print("None of the searched words found")

【问题讨论】:

  • 这里不需要列表理解,因为你没有理解列表,只是想写一个聪明的单行
  • "if val != " "" but val 是一个列表...这就是列表推导的作用,也是它们的目的,它们使用映射创建列表 /filtering 对可迭代对象的操作。 val永远等于字符串
  • 这个问题不是很清楚。您是否有单词列表,并想检查其中是否包含某些单词?
  • 从 Python 3.8 开始,您拥有“海象”运算符 :=。这个问题不是很清楚,但也许这就是你要找的? if(sl := [s for s in list if "test" in s]): print(sl)

标签: python if-statement list-comprehension


【解决方案1】:

首先,避免使用“list”之类的保留字来命名变量。 (保留字始终标记为蓝色)。

如果你需要这样的东西:

mylist = ["age", "test=53345", "anotherentry", "abc"]
keywords = ["test", "anotherentry", "zzzz"]
    
    for el in mylist:
        for word in words:
            if (word in el):
                print(el)

使用这个:

[el for word in keywords for el in mylist if (word in el)]

【讨论】:

    【解决方案2】:

    any 在 python 中允许您查看列表中的元素是否满足条件。如果是,则返回 True,否则返回 False。

    if any("test" in s for s in list): # Returns True if "test" in a string inside list
        print([s for s in list if "test" in s])
    

    【讨论】:

    • 这做同样的工作两次,你可以先做列表推导,只有当你得到任何结果时才打印它
    【解决方案3】:

    首先,请不要使用“列表”作为变量。有一个内置函数叫做 list()...

    可以这样工作:

    list_ = ["age", "test=53345", "anotherentry", "abc"]
    val = [s for s in list_ if "test" in s]                #filters your initial "list_" according to the condition set
    
    if val:
        print(val)                                         #prints every entry with "test" in it
    else:
        print("None of the searched words found")
    

    【讨论】:

    • 为什么用不那么惯用的filter 毫无意义地替换列表理解?另外,if len(val) > 0 应该只是if val,但我认为 OP 实际上想要if len(val) > 1,但不确定
    • 改了,你是对的
    【解决方案4】:

    由于非空列表测试为 True(例如 if [1]: print('yes') 将打印“是”),您可以查看您的理解是否为空:

    >>> alist = ["age", "test=53345", "anotherentry", "abc"]
    >>> find = 'test anotherentry'.split()
    >>> for i in find:
    ...   if [s for s in alist if i in s]:i
    ...
    'test'
    'anotherentry'
    

    但既然找到单个出现就足够了,最好像这样使用any

    >>> for i in find:
    ...   if any(i in s for s in alist):i
    ...
    'test'
    'anotherentry'
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 1970-01-01
      • 2018-07-06
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      相关资源
      最近更新 更多