【问题标题】:Making a list with python and in the list a character should be replaced with a random number用python制作一个列表,列表中的一个字符应该替换为一个随机数
【发布时间】:2020-04-09 02:04:17
【问题描述】:

谁能告诉我如何用随机数替换一个字符,我的意思是

ZYGu*5ed2jvQVWsf1w*A

*替换为随机数,输出为所有可能的组合

ZYGu05ed2jvQVWsf1w0A

ZYGu05ed2jvQVWsf1w1A

ZYGu05ed2jvQVWsf1w2A

...

ZYGu95ed2jvQVWsf1w9A

一直到将数字替换为 9 和 9。我不知道该怎么做,请给点想法?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我试过 x = random.randrange(0,10) y = random.randrange(0,10) print("ZYGu" ,x, "5ed2jvQVWsf1w" ,y, "A")..但它只打印一次,字符串和随机数之间有空格...我想打印所有可能的组合(100)
  • This problem 和你的一样。
  • 谢谢,我找到了我需要的东西。

标签: python


【解决方案1】:

解决简单..您可以观察以下步骤并根据需要进行优化:

  1. 拆分文本
import re
arr = re.split('(\*)', "ZYGu*5ed2jvQVWsf1w*A")
  1. 获取所有星星的计数 *
star_count = arr.count("*")
  1. 创建一个由 2 位数字组成的列表:
import itertools
from itertools import product
a = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
print (list(product(a, repeat=2)))

combinations = list(set(itertools.permutations(a, star_count)))
  1. 通过替换数组的适当元素开始尝试组合,然后最后加入它
for item in combinations:
    new_arr = arr.copy()
    new_arr[1] = str(item[0])
    new_arr[3] = str(item[1])
    print(''.join(new_arr))

希望这会有所帮助!

注意:这是为了演示目的,还有改进的余地。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多