社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

一行语法中的Python if else条件[重复]

TYL • 5 年前 • 1707 次点击  

我知道这个问题已经被问了很多次了,但是我仍然无法正确地将它转换成一行:

string = 'abcdea'
ab = []

for c in list(string):
    if c in ['a','b']:
        ab.append(c) 

一行(不工作):

ab.append(c) if c in ['a','b'] for c in list(string)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52223
 
1707 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Tyler Crompton
Reply   •   1 楼
Tyler Crompton    5 年前

对于单行语法 else 需要套房(例如。 ab.append(c) if c in ['a','b'] else pass for c in list(string) ). 但是,在语法中不允许语句作为操作数。

你在找 list comprehensions (例如。 ab = [c if c in ['a','b'] else None for c in list(string)] ). 然而,这可能会 None 在你的名单上,我不相信你想要。列表理解在这些情况下有特殊的语法糖。只需将测试表达式移到末尾(例如。 ab = [c for c in list(string) if c in ['a','b']] ).

在您的特定情况下,另一种方法是 filter . 这对于测试函数冗长或复杂的情况特别有用。示例如下:

def is_valid_char(c):
    return c in ['a','b','c','d','e','f','A','B','C','D','E','F']

ab = list(filter(is_valid_char, list(string)))

最后,字符串是可iterable的,因此不需要为此目的将字符串转换为列表(例如。 ab = filter(is_valid_char, string) ).

Andrej Kesely
Reply   •   2 楼
Andrej Kesely    5 年前

你在找 list comprehension :

string = 'abcdea'

ab = [c for c in string if c in 'ab']

print(ab)

印刷品:

['a', 'b', 'a']