简体   繁体   English

我如何使python在文件的第一行之后随机选择一行?

[英]How do i make python choose randomly one line after the first line of a file?

Is it possible to make python to randomly choose a line EXCEPT the first line of the file which is reserved for something else? 是否有可能使python随机选择文件保留第一行以外的第一行? Any help appreciated :) 任何帮助表示赞赏:)

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

切片数组:

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

You may also reserve the 1st line beforehand and freely use random selection: 您也可以预先保留第一行,并随意使用随机选择:

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

f.readlines() doesn't read every line from a file; f.readlines()不会从文件中读取每一行; it reads the remaining lines starting with the current file position. 它读取从当前文件位置开始的其余行。

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)

Since a file is its own iterator, though, there is no need to call readline or readlines directly. 但是,由于文件是其自己的迭代器,因此无需直接调用readlinereadlines You can instead simply pass the file to list , using itertools.islice to skip the first line. 您可以直接使用itertools.islice将文件传递到list ,以跳过第一行。

from itertools import islice

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python从文件的每一行中随机选择 - python choose randomly from each line of a file 如何从python的输入文件中选择特定行 - How do I choose a specific line from a input file in python 如何让 Python 在第一行开始读取文件? - How do I get Python to starting reading a file on the first line? 如何使我的输入在一行中(python) - How do I make my input be in one line (python) 我将如何制作一组精灵并随机选择一个? - How would I make a group of sprites and randomly choose one? 如何在 python 中创建 if/then 行 - How do I make a if/then line in python 如何允许Python从2个文本文件(同一行)中选择一条随机行,然后将其存储为变量? - How do I allow Python to choose a random line from 2 text files (that are the same line) and then store them as variables? 如何使代码从python的第一行重新运行? - How do you make code rerun from the first line in python? 无论如何在 python 中是否有从 a.txt 文件中随机检索一行,然后打印它并多次执行此操作而不重复同一行? - Is there anyway in python to retrieve a line from a .txt file randomly, then print it and do this multiple times without repeating the same one? 我正在尝试解决这个 Python 练习,但我不知道该怎么做:从文件中获取行的第一个字符 + 行的长度 - I'm trying to solve this Python exercise but I have no idea of how to do it: get first character of a line from a file + length of the line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM