作为函数参数的Python1行程序

2024-03-29 11:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在这里添加另一个条件:

fword.write(' '.join([chr(c-13+97) if c-13+97>96 else chr(c-3+48) for c in ground_valid])+'\n')
fword.write(' '.join([chr(c-13+97) if c-13+97>96 else chr(c-3+48) for c in output_valid]))

但是我不能完全理解python1的衬里。据我所知,如果我扩展它将是:

for c in ground_valid:
    if c-13+97>96:
        fword.write(' '.join(chr(c-13+97)))
    else if: # my condition
    # instructions
    else:
        fword.write(' '.join(chr(c-3+48)))

我试过了,但没有达到预期的效果。我做错什么了?你知道吗

谢谢你!你知道吗


Tags: inforoutputifmy条件elsewrite
2条回答
fword.write(' '.join([chr(c-13+97) if c-13+97>96 else chr(c-3+48) for c in ground_valid])+'\n')

相当于:

tmp_list = []
for c in ground_valid:
    if c-13+97>96:
        tmp_list.append(chr(c-13+97))
    else:
        tmp_list.append(chr(c-3+48))

tmp_str = ' '.join(tmp_list)
fword.write(tmp_str + '\n')

也就是说,[<expression> for <variable> in <sequence>]是一个列表理解,它的计算结果是一个列表-它是map的简写形式(语法也允许您filter,但在您的示例中没有使用)

本例中的表达式是chr(c-13+97) if c-13+97>96 else chr(c-3+48),这是三元运算符的python格式。^例如,{}等价于C中的<condition> ? <expression1> : <expression2>。你知道吗

您的错误是在循环内调用join,而不是用循环构造一个列表并对结果调用join。你知道吗

这将类似于你的两条单行线:

# fword.write(' '.join([chr(c-13+97) if c-13+97>96 else chr(c-3+48) for c in ground_valid])+'\n')
lst = []
for c in ground_valid:
    if c-13+97>96:
        lst.append(chr(c-13+97))
    else:
        lst.append(chr(c-3+48))
fword.write(' '.join(lst)+'\n')

以及

# fword.write(' '.join([chr(c-13+97) if c-13+97>96 else chr(c-3+48) for c in output_valid]))
lst = []
for c in output_valid:
    if c-13+97>96:
        lst.append(chr(c-13+97))
    else:
        lst.append(chr(c-3+48))
fword.write(' '.join(lst))

你现在更欣赏他们了吗?你知道吗


另一种更紧凑(更易读)的单行程序版本如下:

choises = {True: -13+97, False: -3+48}
fword.write(' '.join([chr(c + choises[c-13+97>96]) for c in ground_valid])+'\n')
fword.write(' '.join([chr(c + choises[c-13+97>96]) for c in output_valid]))

拥有一个没有elifif-else块会让你怀疑字典是否更好。

相关问题 更多 >