Python 具有多个条件的列表理解
Python list comprehension with multiple conditions
我有一个字符串列表
str_list = ['a', 'b', 'c']
并想添加后缀
suffix = '_ok'
当字符串值为'a'
.
这个有效:
new_str_list = []
for i in str_list:
if i == 'a':
new_str_list.append(i + suffix)
else:
new_str_list.append(i)
new_str_list
# ['a_ok', 'b', 'c']
如何使用 列表理解 来简化它?
像
new_str_list = [i + suffix for i in str_list if i=='a' ....
根据它的值创建项目 -
[i + suffix if i=='a' else i for i in str_list ]
[i + suffix if i == 'a' else i for i in str_list]
如您所试,将 if 放在 for 之后是为了跳过值。
在你的情况下,你不会跳过值,而是以不同的方式处理它们。
一个简洁的选项利用了False == 0
:
[i + suffix * (i=='a') for i in str_list]
我有一个字符串列表
str_list = ['a', 'b', 'c']
并想添加后缀
suffix = '_ok'
当字符串值为'a'
.
这个有效:
new_str_list = []
for i in str_list:
if i == 'a':
new_str_list.append(i + suffix)
else:
new_str_list.append(i)
new_str_list
# ['a_ok', 'b', 'c']
如何使用 列表理解 来简化它? 像
new_str_list = [i + suffix for i in str_list if i=='a' ....
根据它的值创建项目 -
[i + suffix if i=='a' else i for i in str_list ]
[i + suffix if i == 'a' else i for i in str_list]
如您所试,将 if 放在 for 之后是为了跳过值。
在你的情况下,你不会跳过值,而是以不同的方式处理它们。
一个简洁的选项利用了False == 0
:
[i + suffix * (i=='a') for i in str_list]