python - python 列表理解中的 if-else

标签 python python-2.7 python-3.x list-comprehension

<分区>

是否可以为以下 python 代码编写列表推导式:

for str in range(0,len(mixed_content)):
    if (mixed_content[str].isdigit()):
        num_list.append(mixed_content[str])
    else:
        string_list.append(mixed_content[str])

我们可以在列表理解中使用 else block 吗?我试着为上面的代码编写列表理解:

num_list , string_list = [   mixed_content[str]  for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]

最佳答案

这是不可能的,但如果你正在寻找单行代码,你可以在循环中使用三元表达式来做到这一点(保存测试并且是紧凑的):

num_list=[]
string_list=[]
for s in ["45","hello","56","foo"]:
    (num_list if s.isdigit() else string_list).append(s)

print(num_list,string_list)

结果:

['45', '56'] ['hello', 'foo']

注意事项:

  • 尽管括号中的语法和问题的上下文,(num_list if s.isdigit() else string_list) 不是生成器,而是一个三元表达式(保护在括号之间以对抗 。 append precedence) 如果 s 是(正)数字序列则返回 num_list,否则返回 string_list
  • 此代码不适用于负数,因为 isdigits 将返回 false。您必须为此编写一个特殊函数(SO 上的经典问题)

关于python - python 列表理解中的 if-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140202/

相关文章:

python - 有没有一种 pythonic 的方法来获取字典中列表中的变量总数?

python - 如何打印 python 数组中的列?

python - 访问 split 函数后的最后一个字符串以创建新列表

python - 在使用 pytest 运行测试之前执行健全性检查

python - PySide 程序崩溃处理程序

python-3.x - RabbitMQ Pika 连接重置 , (-1, ConnectionResetError(104, 'Connection reset by peer' ))

python - 使用正则表达式删除特定单词

python-3.x - 从网络中的数据帧向节点添加属性

python - 绕过pandas concat错误 "Reindexing only valid with uniquely valued Index objects"

python - 通过脚本结果进行远程 NFS 配置