如果我得到一条随机线,是否有可能使它下面的第2行?

时间:2018-11-12 18:47:33

标签: python

如果通过此代码我得到一条随机线:

import random
import time

with open("Songs.txt","r") as f:
    for i in range(random.randint(1,8)):
        line = f.readline()

print("The First Letter Is:",line[0])

然后我如何使用所选的随机线找到下面的第2行?

例如在我的列表中,如果我有:

  1. A
  2. B
  3. C
  4. D
  5. E

如果随机选择的行打印“ A”,我将如何使程序将“ C”存储到变量中,依此类推

感谢评论,我现在有这个,谢谢大家!

import random
import linecache
rand_line = random.randint(1,8)
song = linecache.getline("Songs.txt", rand_line)
Star = len(song)
print("The first letter of the song is:",song[0])
print("The song has",Star,"letters in the title.")
print("And the artist is:",linecache.getline("Songs.txt", rand_line + 9))

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用lines = list(f)将所有行存储在内存中,然后如果您的随机数是i,则获得所需的行就是简单的行[i + 2]。像这样:

import random

with open("Songs.txt","r") as f:
    lines = list(f)

i = random.randint(1, 8)
print("The First Letter Is:",lines[i][0])
print("Other letter is:", lines[i+2])

答案 1 :(得分:0)

在您的特定代码中,您可以像这样在所选行的下方获得第二行:

import random

with open("Songs.txt","r") as f:
    for i in range(random.randint(1,8)):
        line = f.readline()
    next(f, None)
    two_below = next(f, None)

print(line, end='')
print(two_below, end='')

示例输出:

C
E

通常,您可以考虑使用linecache模块来随机访问文本行。

演示:

>>> import linecache
>>> import random
>>> 
>>> rand_line = random.randint(1, 8)
>>> rand_line
3
>>> linecache.getline('Songs.txt', rand_line)
'C\n'
>>> linecache.getline('Songs.txt', rand_line + 2)
'E\n'
>>> linecache.getline('Songs.txt', 1000)
''