将列表中的随机数据打印到fi中

2024-04-19 09:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三张单子

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

我需要写进一个文件,随机从x,y,z到一个新行每一次。你知道吗

Keyword = input("Directory to list")

with open(Keyword) as f: 
        content = f.readlines()

    content = [x.strip() for x in content]

    with open("test.txt") as w:
        w.write(PageFormat + )

输出应如下所示:

2 // 6 // 8

3 // 4 // 9

1 // 5 // 9

2 // 5 // 9

1 // 4 // 7

(“/”包括在内)


Tags: 文件toinforinputaswithopen
2条回答

尝试:-

import random


x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]


file = open("new.txt",'w')

for a in range(0, 10):
    file.write(x[random.randrange(0,3)] + " // " + y[random.randrange(0,3)] + " // " + z[random.randrange(0,3)] + "\n")

file.close()

样本输出:-

2 // 4 // 9
1 // 6 // 9
2 // 5 // 9
1 // 6 // 8
1 // 5 // 8
3 // 5 // 9
3 // 4 // 7
2 // 6 // 7
1 // 5 // 7
2 // 4 // 8

您可以通过更改range()的第二个参数来控制迭代次数。这个程序将在一个新文件中写入10行。你知道吗

from random import choice

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

with open("test.txt", "w") as fp:
    fp.write(choice(x) + "//" + choice(y) + "//" + choice(z))

相关问题 更多 >