【问题标题】:Insert characters randomly into string array a minimum amount of times将字符随机插入字符串数组最少次数
【发布时间】:2020-05-25 11:26:38
【问题描述】:

给定一个字符串数组,我想在一次遍历数组时随机插入字符至少一定次数

# Very large array of strings in reality
text = ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
characters = ['♥', '♫']
# Guaranteed 2 times for example:
result = ['some', '♫', 'list', 'of', '♥', 'strings', 'really', '♥', 'long', 'one', 'at', '♫', 'that']

【问题讨论】:

    标签: python arrays python-3.x string character


    【解决方案1】:
    from random import randrange
    
    text = ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
    characters = ['♥', '♫']
    no_of_reps = 2
    
    def insert_to_random_index(array, characters, no_of_reps):
        for i in range(no_of_reps):
            for character in characters:        
                random_index = randrange(len(array))
                array = array[:random_index] +[character] + array[random_index:]
        return array
    
    new_text = insert_to_random_index(text, characters, no_of_reps)
    print(new_text)
    

    【讨论】:

      【解决方案2】:
      import random
      
      text = ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
      characters = ['♥', '♫']
      
      print(text)
      for i in range(0, random.randint(2, 10)):
          idx = random.randint(0, len(text))
          text = text[:idx] + [random.choice(characters)] + text[idx:]
      
      print(text)
      

      测试输出:

      ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
      ['some', 'list', 'of', 'strings', '♫', 'really', 'long', 'one', '♫', 'at', 'that', '♫']
      

      【讨论】:

        【解决方案3】:

        看看这个,如果您有任何疑问,请随时提问:

          import random
        
        lst = ['!','-','=','~','|']
        string = 'Hello world. Hello world.'
        
        
        print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)
        

        【讨论】:

          猜你喜欢
          • 2018-09-20
          • 2016-02-07
          • 2019-08-04
          • 2019-08-06
          • 2021-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-08
          相关资源
          最近更新 更多