【问题标题】:How do i make python choose randomly one line after the first line of a file?如何让 python 在文件的第一行之后随机选择一行?
【发布时间】:2019-07-31 16:28:13
【问题描述】:

是否可以让 python 随机选择一行,除了文件的第一行,它是为其他东西保留的?任何帮助表示赞赏:)

with open(filename + '.txt') as f:        
    lines = f.readlines()         
    answer = random.choice(lines) 
    print(answer)

【问题讨论】:

    标签: python


    【解决方案1】:

    对数组进行切片:

    answer = random.choice(lines[1:])
    

    【讨论】:

      【解决方案2】:

      您也可以提前保留第一行,随意使用随机选择:

      with open(filename + '.txt') as f:
          reserved_line = next(f)   # reserved for something else
          lines = f.readlines()
          answer = random.choice(lines)
      

      【讨论】:

      • 不错,但我宁愿在阅读所有行之后使用reserved_line = lines[0](至少这样更易读)。
      • @Austin,在这种情况下,lines list 将存储多余的第一行,应在进一步的潜在切片中跳过(条件可能会有所不同)
      • 如果使用next,则使用lines = list(f)读取剩余的行;不要将迭代与直接文件访问混为一谈。
      【解决方案3】:

      f.readlines() 不会从文件中读取每一行;它读取从当前文件位置开始的剩余行。

      with open(filename + '.txt') as f:        
          f.readline()  # read but discard the first line     
          lines = f.readlines()  # read the rest
          answer = random.choice(lines) 
          print(answer)
      

      由于文件是它自己的迭代器,因此无需直接调用readlinereadlines。您可以直接将文件传递给list,使用itertools.islice 跳过第一行。

      from itertools import islice
      
      with open(filename + '.txt') as f:
          lines = list(islice(f, 1, None))
          answer = random.choice(lines)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-01
        相关资源
        最近更新 更多