如果满足条件,列表理解更新值

List comprehension to update values if condition is met

我有以下列表和变量 i:

probs = [1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9]
i = 3

我想将变量 i 中给定索引的列表中的值更改为 3/9,并将其余值更改为 8/9。 因此,符合上述条件的预期结果将是:

probs = [8/9, 8/9, 8/9, 3/9, 8/9, 8/9, 8/9, 8/9, 8/9]

为了提高效率,我更喜欢使用列表理解来做到这一点,有什么想法吗?

您可以使用列表理解中的表达式来执行此操作。

probs = [3 / 9 if i == index else 8 / 9 for index, _ in enumerate(probs)]

这是一个列表理解,可以满足您的要求:

probs = ["1/9", "1/9", "1/9", "1/9", "1/9", "1/9", "1/9", "1/9", "1/9"]
i = 3

probs = ["3/9" if idx == i else "8/9" for idx in range(len(probs))]
print(probs)
# Prints ['8/9', '8/9', '8/9', '3/9', '8/9', '8/9', '8/9', '8/9', '8/9']

请注意,我将分数转换为字符串,否则它们将被打印为浮点数。如果你想让它们成为浮点数,你可以这样做:

probs = [1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9]
i = 3

probs = [3/9 if idx == i else 8/9 for idx in range(len(probs))]
print(probs)
# Prints [0.8888888888888888, 0.8888888888888888, 0.8888888888888888, 0.3333333333333333, 0.8888888888888888, 0.8888888888888888, 0.8888888888888888, 0.8888888888888888, 0.8888888888888888]

另外请注意,这个列表理解实际上并不比普通的 for 循环快。

使用enumerate()

new_probs = ['3/9' if i == indx else '8/9' for indx, val in enumerate(probs)]
print(new_probs)

我建议使用 Python 的 fractions 模块进行概率计算。

因此您的解决方案可以是:

from fractions import Fraction
probs = ["1/9", "1/9", "1/9", "1/9", "1/9", "1/9", "1/9", "1/9", "1/9"]
# rather than integer convert it to Fraction, or simply use fractions only from beginning.
probs = [Fraction(i) for i in probs]  # convert like this
# or use directly as below:
probs = [Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9)]

我相信你很有可能要进行数学运算,所以你可以这样做:

In [12]: print(probs)
[Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9), Fraction(1, 9)]

In [13]: i = 3

In [15]: new_probs = [Fraction(3, 9) if prob==i else Fraction(8, 9) for prob in probs]

In [16]: print(new_probs)
[Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9)]

或者假设您实际上正在执行 1 - Probability 的运算并乘以 3 以匹配,那么它仍然可以与 fraction with 运算一起使用,正如您期望使用概率函数执行的那样:

In [17]: new_probs = [3*prob if prob==i else 1-prob for prob in probs]

In [18]: print(new_probs)
[Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(2, 3), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9), Fraction(8, 9)]