Python 代码不返回整个列表[Codio]
提示符:加载以管道分隔的文件p。每行有3个字段:firstname | lastname |生日 搜索firstname F和lastname L,将生日替换为B。以相同的管道分隔格式将文件写回 我的代码正确返回列表的第一行,但Codio显示一个错误,说明: 您的输出: 亚当·斯密11111985 预期输出: 亚当·斯密11111985 西奥多|安德森| 20031990 亚当·K |斯密| 09091999 蒙蒂|饼干桶| 18101980 亚当·斯密瑟斯| 00000000 Ruthy | Anderson | 06062010 所以我被引导相信我的代码出于某种原因没有打印整个列表?我不知道如何修复它,但是Python 代码不返回整个列表[Codio],python,codio,Python,Codio,提示符:加载以管道分隔的文件p。每行有3个字段:firstname | lastname |生日 搜索firstname F和lastname L,将生日替换为B。以相同的管道分隔格式将文件写回 我的代码正确返回列表的第一行,但Codio显示一个错误,说明: 您的输出: 亚当·斯密11111985 预期输出: 亚当·斯密11111985 西奥多|安德森| 20031990 亚当·K |斯密| 09091999 蒙蒂|饼干桶| 18101980 亚当·斯密瑟斯| 00000000 Ruthy |
import sys
P= sys.argv[1]
F= sys.argv[2]
L= sys.argv[3]
B= sys.argv[4]
# ----------------------------------------------------------------
#
# Our Helper functions:
#
# ----------------------------------------------------------------
#
# Loads the file at filepath
# Returns a 2d array with the data
#
def load2dArrayFromFile(filepath):
records = []
with open(filepath, 'r') as txt:
elem = txt.readlines()
for row in elem:
recordsList = row.strip('\n').split('|')
records.append(recordsList)
return records
# Searches the 2d array 'records' for firstname, lastname.
# Returns the index of the record or -1 if no record exists
#
def findIndex(records, firstname, lastname):
import re
for x in range(len(records)):
row = records[x]
if row[0] == F and row[1] == L:
return x
else:
return -1
# Sets the birthday of the record at the given index
# Returns: nothing
def setBirthday(records, index, newBirthday):
# Your code goes here:
if index == None:
return
records[index][2]=newBirthday
# Convert the 2d array back into a string
# Return the text of the 2d array
def makeTextFrom2dArray(records):
# Your code goes here:
new2D = [ ]
Char = ""
for row in records:
new2D.append(("|").join(row))
Char = ("\n").join(new2D)
return Char
# ----------------------------------------------------------------
#
# Our main code body, where we call our functions.
#
# ----------------------------------------------------------------
# Load our records from the file into a 2d array
records= load2dArrayFromFile(P)
# Find out which index, if any, has the name we are hunting
indexWeAreHunting= findIndex(records, F, L)
# Set the birthday record to the one we were passed
setBirthday(records, indexWeAreHunting, B)
# Convert the records into a text string
output= makeTextFrom2dArray(records)
# Your code goes here
# write the text string out to the file
newFile = open(P, 'w')
newFile.write (output)
newFile.close
我看到至少有两个地方在循环中有一个无条件的
return
语句。这使得循环毫无意义;只有第一次迭代才会发生。