📜  Python – 在字符串列表中连接随机字符

📅  最后修改于: 2022-05-13 01:54:28.110000             🧑  作者: Mango

Python – 在字符串列表中连接随机字符

给定一个字符串列表,执行随机字符的连接。

方法 #1:使用循环 + random.choice()

在此,我们使用choice() 提取随机字符并使用循环执行迭代任务。字符连接是使用 +运算符完成的。

Python3
# Python3 code to demonstrate working of
# Concatenate Random characters in String List
# Using loop + choice()
import random
 
# initializing list
test_list = ["Gfg", "is", "Best", "for", "Geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = ''
for ele in test_list:
     
    # Concatenating random elements
    res += random.choice(ele)
         
# printing results
print("Concatenated String : " + str(res))


Python3
# Python3 code to demonstrate working of
# Concatenate Random characters in String List
# Using list comprehension + choice() + join()
import random
 
# initializing list
test_list = ["Gfg", "is", "Best", "for", "Geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# characters joining using join()
res = ''.join([random.choice(ele) for ele in test_list])
         
# printing results
print("Concatenated String : " + str(res))


输出
The original list is : ['Gfg', 'is', 'Best', 'for', 'Geeks']
Concatenated String : Gsere

方法 #2:使用列表理解 + 选择() + 加入()

在此,我们使用choice() 执行获取随机的任务,并使用join() 完成连接。

Python3

# Python3 code to demonstrate working of
# Concatenate Random characters in String List
# Using list comprehension + choice() + join()
import random
 
# initializing list
test_list = ["Gfg", "is", "Best", "for", "Geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# characters joining using join()
res = ''.join([random.choice(ele) for ele in test_list])
         
# printing results
print("Concatenated String : " + str(res))
输出
The original list is : ['Gfg', 'is', 'Best', 'for', 'Geeks']
Concatenated String : Gitrk