我使用random.randint生成一个随机数,然后将该数字赋给变量。然后我想打印带有我赋给变量的数字的行,但我不断收到错误:
列出索引超出范围
这是我尝试的内容:
f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(1,10)
print lines[rand_line]
答案 0 :(得分:6)
您想使用random.choice
import random
with open(filename) as f:
lines = f.readlines()
print(random.choice(lines))
答案 1 :(得分:0)
这段代码是正确的,假设您打算将字符串传递给open
函数,并且在点后面没有空格...
但是,要小心Python中的索引,即它从0开始而不是1,然后在len(your_list)-1
结束。
使用random.choice
会更好,但如果您想要遵循您的想法,那就更好了:
import random
with open('name.txt') as f:
lines = f.readlines()
random_int = random.randint(0,len(lines)-1)
print lines[random_int]
由于randint
包含两个边界,因此您必须查看len(lines)-1
。
答案 2 :(得分:0)
f = open(filename. txt)
lines = f.readlines()
rand_line = random.randint(0, (len(lines) - 1)) # https://docs.python.org/2/library/random.html#random.randint
print lines[rand_line]
答案 3 :(得分:0)
要获得随机行而不将整个文件加载到内存中,可以使用Reservoir sampling(样本大小为1):
import System.Environment
import System.Directory
import System.IO
import Data.List
main :: IO ()
main = do
putStrLn "Insert a string"
word <- getLine
putStrLn "Insert a char"
char <- getChar
putStrLn "Insert a position"
pos <- getLine *line which is skipped*
let x = (read pos :: Int) *converts string into int*
putStrLn "Adding char to list..."
let newS = [(insertChar char word x)] *result of insertChar is set to
newS*
putStrLn "Printed list: "
print (newS) *print new string*
putStrLn "Insert file name"
file <- getLine
putStrLn "Adding new string to file..."
add file newS
insertChar :: a -> [a] -> Int -> [a]
insertChar x ys 1 = x:ys
insertChar x (y:ys) n = y:insertChar x ys (n-1)
add :: String -> [String] -> IO ()
add fileName [item] = appendFile fileName item
此算法使用GHCI>main
Insert a string
hello world
Insert a char
s
Insert a position
Adding char to list...
Printed list:
["*** Exception: Prelude.read: no parse
的额外空间在import System.Environment
import System.Directory
import System.IO (hSetBuffering, stdin, BufferMode(NoBuffering)) *New line*
import Data.List
main :: IO ()
main = do
hSetBuffering stdin NoBuffering *New line*
putStrLn "Insert a string"
word <- getLine
putStrLn "Insert a char"
char <- getChar
putStrLn "Insert a position"
pos <- getLine
let x = (read pos :: Int)
putStrLn "Adding char to list..."
let newS = [(insertChar char word x)]
putStrLn "Printed list: "
print (newS)
putStrLn "Insert file name"
file <- getLine
putStrLn "Adding new string to file..."
add file newS
insertChar :: a -> [a] -> Int -> [a]
insertChar x ys 1 = x:ys
insertChar x (y:ys) n = y:insertChar x ys (n-1)
add :: String -> [String] -> IO ()
add fileName [item] = appendFile fileName item
时间内运行。
答案 4 :(得分:0)
您可以编辑代码以实现此目的而不会出错。
f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(0,len(lines)-1) # this should make it work
print lines[rand_line]
这样索引就不会超出范围。