【问题标题】:Is it possible to write multiple statements in one line that includes a for loop and if-else statements是否可以在一行中编写多个语句,包括 for 循环和 if-else 语句
【发布时间】:2021-02-17 21:41:03
【问题描述】:

我一直在尝试一些字符串操作,并试图将其浓缩为一行:

y = 0
resultswords = []
for words in newstring:
    if words.lower() not in '_':
        resultswords.append(words)
    else:
        resultswords.append(str(answers[y]))
        y += 1

我一直在尝试找出如何去做,但我一无所获。我能得到的最接近的是

resultwords = [word if word not in '_' else str(answers[y]) for word in newstring]

我开始认为这是不可能的,因为我在谷歌的任何地方都找不到任何关于它的文章,但我还是要求确认它。感谢阅读。

【问题讨论】:

  • @mkrieger1 通知y? OP 可能对此有困难。
  • 假设缩进是正确的,y 在else 子句中只增加一这一事实让我认为任何单行代码都会比它的价值更令人困惑。跨度>
  • 在一行 line 中执行此操作是微不足道的; Python 确实有一个语句分隔符。您似乎想在一个 statement 中执行此操作,这是完全不同的。 (1) 程序逻辑的目标是什么——所有所需的输入和输出是什么? (2) 在一份声明中这样做的理由是什么?如果您同时生成两个已更改的变量(y 和 resultswords),那么单语句解决方案会很尴尬。
  • 看看here
  • words.lower() not in '_' 是什么意思? '_' 中怎么会有一个词?也许你想检查是'_' in words 还是words == '_'?

标签: python for-loop if-statement list-comprehension one-liner


【解决方案1】:

python 无法做到这些:

i++
++i

所以我认为你可以这样做

answers = {i: i+990 for i in range(4)}
print(answers)  # {0: 990, 1: 991, 2: 992, 3: 993}

y = 0
nums = [1, 2, 3, 4]
res = []
for num in nums:
    if num < 3:
        res += [num]
    else:
        res += [str(answers[y])]
        y += 1
print(res)  # [1, 2, '990', '991']

一行这样:

def addy():
    global y
    y += 1
    return str(answers[y-1])


y = 0
res = [(num if num < 3 else addy()) for num in nums]
print(res)  # [1, 2, '990', '991']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    相关资源
    最近更新 更多