代码之家  ›  专栏  ›  技术社区  ›  Jackfin321

Python中列表中具有x个字符串的变量

  •  0
  • Jackfin321  · 技术社区  · 1 年前

    假设我有一个包含5个字符串的列表,我想从这个列表中打印随机数目的随机生成的字符串。有简单的方法吗?

    我知道从这个列表中打印单个随机字符串的多种方法,也知道从这个集合中打印一组随机字符串的几种方法。问题来自于想要从列表中打印随机数目的随机字符串。

    要获得一组随机字符串(假设为2),我将执行以下操作:

     import random
     my_list = ['a','b','c','d','e']
     two_rand_strings = str(my_list[random.randint(0,4)]) + " " + str(my_list[random.randint(0,4)])
     print(two_rand_strings)
    

    我想我需要创建某种函数来生成随机数量的字符串,但我对python还很陌生,而且还很头疼。

    3 回复  |  直到 1 年前
        1
  •  1
  •   tdelaney    1 年前

    有一个API。

    这个 random 模块有几个选项可以从总体中选择,例如列表。如果您想对字符串结果中的每个项目使用相同的分隔符,您可以 str.join 他们

    import random
    my_list = ['a','b','c','d','e']
    unique = " ".join(random.sample(my_list, k=2))
    nonunique = " ".join(random.choices(my_list, k=2))
    
        2
  •  1
  •   hamed danesh    1 年前

    如果你的意思是随机选择的字符串的随机数,这可能会帮助你:

    import random
    
    my_list = ["a", "b", "c", "d", "e"]
    
    randomCount = random.randint(0, 5)
    
    myString = ""
    for i in range(0, randomCount):
        myString = myString + " " + str(my_list[random.randint(0, 4)])
    
    print(myString)
    
        3
  •  0
  •   Yasser Khalil    1 年前

    以下是另一种方法:

    i = 0 # set i (counter to zero)
    my_list = ['a','b','c','d','e'] # your list
    print_str = "" # define the printed variable
    for x in my_list: # loop through your list
        i += 1 # increase counter by one
        print_str += x + " " # add new strings to the printed variable
        if i == 2: # when it reach the required number of strings, breaks the loop
            break
    
    print(print_str) # print the strings