random.randint를 사용하여 난수를 생성 한 다음 그 수를 변수에 할당합니다.txt 파일의 임의의 줄을 인쇄 하시겠습니까?
f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(1,10)
print lines[rand_line]
random.randint를 사용하여 난수를 생성 한 다음 그 수를 변수에 할당합니다.txt 파일의 임의의 줄을 인쇄 하시겠습니까?
f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(1,10)
print lines[rand_line]
당신은 random.choice
list index out of range
: 그럼 내가 변수에 할당 된 번호로 선을 인쇄 할,하지만 난 오류가 계속
import random
with open(filename) as f:
lines = f.readlines()
print(random.choice(lines))
이 코드는 open
함수에 문자열을 전달하려는 것으로 가정하고, 점 뒤에 공백이없는 것으로 가정하면 ... 그러나주의하십시오 파이썬에서의 인덱싱, 즉 0에서 시작하지 않고 1에서 시작하여 len(your_list)-1
에서 끝납니다.
random.choice
이 더 사용하지만, 당신이 당신의 아이디어를 따라하려는 경우 오히려 것 : randint
이후
import random
with open('name.txt') as f:
lines = f.readlines()
random_int = random.randint(0,len(lines)-1)
print lines[random_int]
모두 경계를 포함, 당신은 len(lines)-1
까지보고해야합니다.
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]
파일에 몇 줄이 있습니까? (또는 오히려, 얼마나 많은 요소가'lines' 목록에 있습니다) – UnholySheep
시도해보십시오. randint (0, len (lines)) –
@ A.Kot 여전히 잘못 될 수 있습니다. –