1

babynames2000s.txt(неполный):

1   Jacob   273,450 Emily   223,488
2   Michael 250,174 Madison 192,976
3   Joshua  231,602 Emma    181,055
4   Matthew 221,266 Olivia  155,848
5   Daniel  203,404 Hannah  155,525
6   Christopher 203,006 Abigail 150,746
7   Andrew  202,208 Isabella    149,310
8   Ethan   201,611 Samantha    134,148
9   Joseph  194,377 Elizabeth   133,166
10  William 194,079 Ashley  132,934

в первом столбце находятся мужские имена. задача записывать в новый лист boysfile элементы из listfile начиная с первого индекса и далее через 3.

infile = open("babynames2000s.txt", "r") 
outfile_boys = open("boynames2014.txt", "w")
outfile_girls = open("girlnames2014.txt", "w")

listfile = []
lines = infile.read().split('\t')
indexx = 1
boysfile = []

for line in lines:
    listfile.append(line.rstrip())

print(listfile[indexx])
for item in listfile:
    boysfile = listfile[indexx]
    indexx = indexx + 3
outfile_boys.write(boysfile) 

print(boysfile)

выдаёт:

Jacob

Traceback (most recent call last): File "C:/Users/spart/Documents/python/homework4/boys_and_girls.py", line 15, in boysfile = listfile[indexx]

IndexError: list index out of range

так же пытался вместо boysfile = listfile[indexx] , использовать boysfile.append(listfile[indexx]) выдавало ту же самую ошибку

2
  • Вы что-то странное пытаетесь сделать. Вы понимаете, что у вас indexx будет расти на 3 за каждый элемент в listfile, и когда вы дойдёте примерно до трети этого списка, indexx превысит максимальный размер listfile?
    – Xander
    1 фев 2019 в 12:08
  • 2
    boys_list = [l.strip().split() for l in infile.readlines()][1::3]
    – Lecron
    1 фев 2019 в 13:02

1 ответ 1

0

Если я все понял правильно то должно быть так:

for item in listfile[0::3]: # Начнет с первого элемента (0 это первый элемент списка) с шагом 3 
    boysfile.append(item)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.