python 我如何改变4个随机变量中的2个?

w9apscun  于 2023-02-03  发布在  Python
关注(0)|答案(6)|浏览(201)

我需要将四个随机变量中的两个变量的值改为“-”。我怎样才能做到最有效和可读性最强呢?下面的代码只是垃圾,仅供参考。

from random import choice
a = 10
b = 18
c = 15
d = 92

choice(a, b, c, d) = '—'
choice(a, b, c, d) = '—'

print(a, b, c, d)

>>> 12 — — 92
>>> — 19 — 92
>>> 10 18 — —

我试过***choice(a,B,c,d)= '-'***但是没有用。可能有一个解决方案使用列表函数和方法,但是它很复杂,几乎不可能读,所以我正在寻找一个更简单的解决方案。

tzxcd3kk

tzxcd3kk1#

考虑到你需要创建4个独立的变量,你可以这么做:

from random import sample
a = 10
b = 18
c = 15
d = 92
for i in sample(['a','b','c','d'], k=2):
    exec(f"{i} = '-'")
print(a,b,c,d)

使用sample可以确保值不重复。但是,不推荐使用这种方法,而只是为了帮助您更好地理解问题。我建议使用其他开发人员所述的列表或字典。

k7fdbhmy

k7fdbhmy2#

变量名在运行代码时不可用,因此不能更改“随机变量”。相反,我建议您使用列表或字典。然后您可以从列表中选择随机元素或从字典中选择随机键。

kr98yfug

kr98yfug3#

给定四个命名变量的约束,我可能会这样做:

from random import sample
a = 10
b = 18
c = 15
d = 92

v = sample("abcd", 2)
if "a" in v:
    a = "_"
if "b" in v:
    b = "_"
if "c" in v:
    c = "_"
if "d" in v:
    d = "_"

print(a, b, c, d)

这是可读的,但也是极其重复的。如果没有四个单独的变量,这就容易得多了:

from random import sample
nums = {
    "a": 10,
    "b": 18,
    "c": 15,
    "d": 92,
}

for v in sample(nums, 2):
    nums[v] = "_"

print(*nums.values())
nr9pn0ug

nr9pn0ug4#

import random

data = [10, 18, 15, 92]

already_changed = []
for i in range(2): # change 2 to however many numbers you want to change

    index=random.randint(0,len(data)-1) # randomly select an index to change
    while index in already_changed: # makes sure not to change the same index
        index = random.randint(0, len(data) - 1)

    data[index] = "_" 

print(data)
jhiyze9q

jhiyze9q5#

不能执行choice(a, b, c, d) = '-',因为choice不是变量,因此不能赋值。
你应该把变量存储在一个列表中,然后用你的字符串替换随机元素,可以这样做:

from random import randint

a = 10
b = 18
c = 15
d = 92

replacement = "--"
nums = [a, b, c, d]

while nums.count(replacement) < 2:
    # create random index
    index = randint(0, len(nums)-1)
    # replace value at index with the replacement
    nums[index] = replacement

print(*nums) # print each element in the list

但是,请注意,此代码不会更改a、b、c、d的值。如果您希望这样做,则需要重置变量。

ki0zmccv

ki0zmccv6#

你可以从一个项目列表中随机选取任意两个索引,并用_替换索引位置的元素来实现这一点:

import random

x = [10,18,15,92]

for i in random.sample(range(len(x)), 2):
    x[i] = '_'

print(x)

相关问题