简体   繁体   English

列表理解有两个条件

[英]List comprehension with two conditions

It's possible to use list comprehension in python with two expression? 可以在带有两个表达式的python中使用列表理解吗?

IE: I have a list with dots '.' IE:我有一个带有点“。”的列表。 and semicolon ';' 和分号“;” and I want to create a boolean list using the first one as a parameter: 我想使用第一个作为参数创建一个布尔列表:

  • Dot = True 点=真
  • Semicolon = False 分号=错误

I know how to create using only one expression: 我知道如何仅使用一个表达式创建:

L1 = [True if i == '.' for i in L2]

Or 要么

L1 = [False if i == ';' for i in L2]

It's possible to merge those clausules in one list comprehension? 是否可以将这些子句合并为一个列表理解?

Edit: [.;.;.] should transform into [True, False, True, False, True] 编辑:[。;。;。]应该转换为[True,False,True,False,True]

要另外防止其他字符,请使用:

L1 = [ch == '.' for ch in L2 if ch in '.;']
[char == '.' for char in l]

char == '.' evaluates to True if the character is a period and False otherwise. 如果字符是句点,则结果为True,否则为False。

If you need a more complex transformation, you can use 如果您需要更复杂的转换,可以使用

mapping = {
    '.': True,
    ';': False,
    ...
}

[mapping[char] for char in l]

If you need to filter out characters other than the ones you're looking for, 如果您需要过滤除所需字符以外的其他字符,

[mapping[char] for char in l if char in mapping]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM