2

我有一个菜单,除非输入是 d 或 D,否则将返回“e”。我想在不创建另一个变量并在一行上执行的情况下执行此操作

encrypt = 'd' if (raw_input("Encrypt or Decrypt a file(E/d):") == ('d' or 'D')) else 'e'

[编辑] 好的,这是一个更难的

我该怎么做

file_text = 'a.txt' if (raw_input("File name(a.txt):")=='a.txt' else [What I typed in]
4

2 回答 2

3

使用in运算符:

encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):") in ('d', 'D') else 'e'

或者,您可以将输入转换为小写并将其与“d”进行比较:

encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):").lower() == 'd' else 'e'

最后,如果要确保它们输入 e 或 d,可以将其包装在 while 循环中:

while True:
    encrypt = raw_input("Encrypt or decrypt a file (E/d):")

    # Convert to lowercase
    encrypt = encrypt.lower()

    # If it's e or d then break out of the loop
    if encrypt in ('e', 'd'):
        break

    # Otherwise, it'll loop back and ask them to input again

编辑:要回答你的第二个问题,我猜你可以使用 lambda 吗?

file_text = (lambda default, inp: default if inp.lower() == default else inp)("a.txt", raw_input("File name(a.txt):"))

虽然,这显然有点迟钝,也太“聪明”了一半。

于 2012-04-03T19:47:40.693 回答
1

不是很认真,而是另一种单行解决方案(我认为它不可读):

encrypt = {'d':'d','D':'d'}.get(raw_input("Encrypt or decrypt a file (E/d):"), 'e')

至少它很短。有时字典实际上对类似情况很有用(如果有更多选择)。

于 2012-04-03T19:59:40.187 回答