【问题标题】:How to select lines from a text file and then randomize the order of those lines? (in python)如何从文本文件中选择行,然后随机化这些行的顺序? (在蟒蛇中)
【发布时间】:2022-01-17 05:26:55
【问题描述】:

我遇到的问题是我想从文本文件中选择一个范围内的多行,然后随机化这些行的顺序。我知道这是如何随机化文本文件,但是如何针对一定数量的行进行随机化呢?

with open("infile.txt") as f:
    lines = f.readlines()
random.shuffle(lines)
with open("outfile.txt", "w") as f:
    f.writelines(lines)```

【问题讨论】:

  • 这只是一个列表。要将第 10 行到第 20 行随机播放,请执行 lines = lines[:10] + random.shuffle(lines[10:20]) + lines[20:]
  • @Tim 不起作用,如果起作用了,那就太复杂了。
  • @TimRoberts 它不起作用,它给出错误“只能将列表(而不是“NoneType”)连接到列表”
  • 不清楚你的选择是什么意思。
  • @KellyBundy 例如,我只想随机化文本文件的第 1-5 行。所以我想定位或选择这些行并将它们随机化。

标签: python random


【解决方案1】:

不确定这是最好的解决方案,但它确实有效

n_start=1
n_end=4
with open("infile.txt") as f:
    lines = f.readlines()
tmp=lines[n_start:n_end]
random.shuffle(tmp)
lines[n_start:n_end]=tmp
with open("outfile.txt", "w") as f:
    f.writelines(lines)

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2012-09-03
    • 2012-01-10
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多