新手求助:怎么用python随机生成一系列字符串

FFanIU 发布于 2016/01/14 08:58
阅读 291
收藏 0
文件类似于:
asdf 
qwer
cdfgh 
sdwe
。。。每个字符串占一行,我想从文件中提供的字符串,随机选择两个字符串,随机生成很多个字符串对,例如asdf_qwer,asdf_cdfgh.....,而且自己不能跟自己配对
加载中
0
Kinegratii
Kinegratii
C:\Users\TM>python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = ['a','b','c','d', 'e']
>>> import itertools
>>> import random
>>> s = list(map(lambda x:'_'.join(x), itertools.permutations(s, 2)))
>>> s
['a_b', 'a_c', 'a_d', 'a_e', 'b_a', 'b_c', 'b_d', 'b_e', 'c_a', 'c_b', 'c_d', 'c_e', 'd_a', 'd_b', 'd_c', 'd_e', 'e_a', 'e_b', 'e_c', 'e_d']
>>> random.choice(s)
'e_d'
>>> random.choice(s)
'b_c'
>>> random.sample(s,3)
['c_e', 'b_d', 'b_c']
>>> random.sample(s,3)
['a_d', 'd_c', 'd_e']
>>>


刚开始的s通过下面代码

with open('demo.txt', 'r') as f:
    s = list(map(lambda x:x.strip('\n'), f.readlines()))





0
0x0001
0x0001
import random


def random_test(file_name, count):
    with open(file_name, 'r') as f:
        lst = [line.strip() for line in f if len(line.strip()) > 0]

        if len(lst) < 2:
            raise Exception('error! 文本行数少于2')

        return ['_'.join(random.sample(lst, 2)) for _ in xrange(count)]

if __name__ == '__main__':
    print '\r\n'.join(random_test('test.txt', 10))



返回顶部
顶部