0

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

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]

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

4

1 回答 1

0

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']
于 2021-03-12T17:25:26.733 回答