使用存储在"travel_plans.txt"中的数据创建一个名为目标的列表。列表的每个元素都应包含文件中的一行,该行列出了一个国家/地区以及该国家/地区内的城市。
"travel_plans.txt"包含:
This summer I will be travelling.
I will go to...
Italy: Rome
Greece: Athens
England: London, Manchester
France: Paris, Nice, Lyon
Spain: Madrid, Barcelona, Granada
Austria: Vienna
I will probably not even want to come back!
However, I wonder how I will get by with all the different languages.
I only know English!
到目前为止,我已经设法编写了以下内容:
with open("travel_plans.txt","r") as fileref:
for line in fileref:
row = line.strip().split()
if ":" in row[0]:
destination = row
print(destination)
有没有更好的方法来获得相同的输出?
destination = []
with open("travel_plans.txt","r") as fileref:
for line in fileref:
row = line.strip()
if ":" in row:
destination.append(row)
print(destination)
对于一个小文件,任何超过这个文件的东西都可能是矫枉过正。
你可以把它做得更短。
destination = [line.strip() for line in fileref if ":" in line]
print(destination)
接受的答案非常好。由于您正在学习,我还有其他一些建议。
首先,您可以考虑一种稍微更pythonic(通常意味着"可读"(的方法,其中可能包括将其分解为多个函数。
def test_line(line):
"""This function returns `None` for lines we don't care about."""
if ":" in line:
return line
上面的第二行称为"文档字符串"。它向代码的其他读者解释(包括提醒将来的你(代码的作用。
然后是处理行的函数:
def hande_lines(lines):
"""A list of lines we care about."""
return [line for line in lines if test_line(line) is not None]
以及用于处理文件的函数:
def handle_file(name):
"""Parse a file into a list of lines we care about."""
with open(name) as f:
return hande_lines(f)
第二个建议:写一个测试。要测试脚本,请在.py文件的底部包含以下内容(我们称此文件为"模块"(:
if __name__=="__main__":
# this is just test of the module
file_name = "travel_plans.txt"
for value in handle_file(file_name):
print(value)
通过在与脚本(和测试文件(相同的目录中打开命令行并运行以下命令来运行它,其中"myapp"是.py文件的名称:
python myapp.py
最后一点:与其使用print
函数,编写测试的更好方法是使用 assert 语句。
if __name__=="__main__":
# this is just test of the module
file_name = "travel_plans.txt"
result = handle_file(file_name):
# make sure all the lines were found:
assert len(result) == 6
# make sure all the lines have the colon in them:
assert all(":" in r for r in result)
# finally, test a couple of the results that they are what we expect:
assert result[0] == "Italy: Rome"
assert result[-1] == "Austria: Vienna"
如果这些断言语句中的任何一个产生了AssertionError
,那么你就知道你编写的代码正在做一些你不希望它做的事情。
学习编写好的测试,以便您知道您的代码正在做您希望它做的事情,这是一个非常好的习惯,可以立即养成。