Python替换列表中的随机特定元素

取力器

我有一个包含许多字母的列表,我想用“b”替换随机的“a”,我该怎么做?

alphabets = ["a", "c", "a", "a", "b", "c"]

想要的输出示例:

["a", "c", "a", "b", "b", "c"]
["b", "c", "a", "a", "b", "c"]
["a", "c", "b", "a", "b", "c"]
房间

我希望这个对你有用。如果有任何问题,请告诉我。

我假设它alphabets总是有一个'a'并且你总是想随机地将一个更改'a'为一个'b'

from random import randint

alphabets = ["a", "c", "a", "a", "b", "c"]

# get indices in alphabets associated with the value "a"
indices = [i for i, x in enumerate(alphabets) if x == 'a']

print(f"{'Before':6}: {alphabets}")

# randomly change one of the "a"s to a "b" 
alphabets[indices[randint(0, len(indices) - 1)]] = "b"

print(f"{'After':6}: {alphabets}")

示例输出:

Before: ['a', 'c', 'a', 'a', 'b', 'c']
After : ['b', 'c', 'a', 'a', 'b', 'c']

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章