Создайте копию списка. Используя testList = inputList[:]
. См. Код
>>> def plusOne(y):
newY = y[:]
for x in range(len(newY)):
newY[x] += 1
return newY
>>> y = [1, 2, 3]
>>> print plusOne(y), y
[2, 3, 4] [1, 2, 3]
Или вы можете создать новый список в функции
>>> def plusOne(y):
newList = []
for elem in y:
newList.append(elem+1)
return newList
. Вы также можете использовать понимание, как указывали другие.
>>> def plusOne(y):
return [elem+1 for elem in y]
Вам понадобится:
- разбить каждую строку на пробелы и вырезать все элементы, кроме первого
- преобразовать каждое строковое значение в массиве в целое число
- суммировать все эти целочисленные значения в массиве
- добавить сумму для этой строки в total_sum
- добавить длину этих значений (количество чисел) к total_numbers
inFile = open('classgrades.txt','r')
outFile = open('classscores.txt','w')
total_sum = 0
total_values = 0
with open(r'classgrades.txt') as inFile:
for line in inFile:
# split by whitespace and slice out everything after 1st item
num_strings = line.split(' ')[1:]
# convert each string value to an integer
values = [int(n) for n in num_strings]
# sum all the values on this line
line_sum = sum(values)
# add the sum of numbers in this line to the total_sum
total_sum += line_sum
# add the length of values in this line to total_values
total_numbers += len(values)
average = total_sum // total_numbers # // is integer division in python3
return average
вам не нужно открывать файл много раз, и вы должны закрыть файлы в конце вашей программы. Ниже я попробовал надеяться, что это сработает для вас:
d1 = {}
with open(r'classgrades.txt','r') as fp:
for line in fp:
contents = line.strip().split(' ')
# create mapping of student and his numbers
d1[contents[0]] = map(int,contents[1:])
with open(r'classscores.txt','w') as fp:
for key, item in d1.items():
biggest = min(item)
smallest = max(item)
print(biggest - smallest)
# average of all numbers
avg = sum(item)/len(item)
fp.write("%s %s\n"%(key,avg))
Извиняюсь, если это довольно сложный вопрос, я стараюсь предоставить ключевые слова / фразы, чтобы вы могли искать, чтобы узнать больше.
Предполагая, что вы ищете отдельное среднее значение для каждого студента:
in_file = open('classgrades.txt', 'r') # python naming style is under_score
out_file = open('classcores.txt', 'w')
all_grades = [] # if you want a class-wide average as well as individual averages
for line in in_file:
# make a list of the things between spaces, like ["studentname", "90", "100"]
student = line.split(' ')[0]
# this next line includes "list comprehension" and "list slicing"
# it gets every item in the list aside from the 0th index (student name),
# and "casts" them to integers so we can do math on them.
grades = [int(g) for g in line.split(' ')[1:]]
# hanging on to every grade for later
all_grades += grades # lists can be +='d like numbers can
average = int(sum(grades) / len(grades))
# str.format() here is one way to do "string interpolation"
out_file.write('{} {}\n'.format(student, average))
total_avg = sum(all_grades) / len(all_grades)
print('Class average: {}'.format(total_avg))
in_file.close()
out_file.close()
Как отмечали другие, полезно привыкнуть к закрытию файлов. Другие ответы здесь используют with open()
(в качестве «диспетчера контекста»), что является наилучшей практикой, поскольку оно автоматически закрывает файл для вас. Чтобы работать с двумя файлами без контейнера данных (например, словарь Амита d1
), вы должны сделать что-то вроде:
with open('in.txt') as in_file:
with open('out.txt', 'w') as out_file:
... do things ...
Этот скрипт должен выполнить то, что вы пытаетесь сделать, я думаю:
# define a list data structure to store the classgrades
classgrades = []
with open( 'classgrades.txt', 'r' ) as infile:
for line in infile:
l = line.split()
# append a dict to the classgrades list with student as the key
# and value is list of the students scores.
classgrades.append({'name': l[0], 'scores': l[1:]})
with open( 'classscores.txt', 'w' ) as outfile:
for student in classgrades:
# get the students name out of dict.
name = student['name']
# get the students scores. use list comprehension to convert
# strings to ints so that scores is a list of ints.
scores = [int(s) for s in student['scores']]
# calc. total
total = sum(scores)
# get the number of scores.
count = len( student['scores'] )
# calc. average
average = total/count
biggest = max(scores)
smallest = min(scores)
diff = ( biggest - smallest )
outfile.write( "%s %s %s\n" % ( name, diff , average ))
Выполнение приведенного выше кода создаст файл с именем classscores.txt, который будет содержать это:
Chapman 45 79.33333333333333
Cleese 10 85.75
Gilliam 7 78.66666666666667
Idle 0 91.0
Jones 100 63.57142857142857
Palin 10 85.0