从文本文件创建列表

时间:2019-12-25 08:15:50

标签: python

问题

使用travel_plans.txt中存储的数据创建一个名为“目的地”的列表。列表中的每个元素都应包含文件中的一行,该行列出了一个国家/地区和该国家/地区内的城市。提示:每条包含此信息的行中也都带有一个冒号:。

travel_plans.txt

g n = sequence $ map f [1..n]

到目前为止我的代码

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!  

2 个答案:

答案 0 :(得分:0)

您的for循环将无法像这样工作。如果用逗号分隔,则冒号永远不会以自己的形式结尾。相反,他们会像England: London那样与某个国家/地区保持联系,幸运的是,您不需要这样做。像这样的for循环

for li in lines:
    if ':' in li:
        destination.append(li)

将为您解决问题。 if条件检查行中是否存在冒号,在这种情况下,根据描述,该行将是所需的行之一,并相应地将其追加到列表中

答案 1 :(得分:0)

您非常接近。

  • 处理文件时最好使用上下文管理器。
  • 您不需要第二个for循环。

这就是我要做的:

with open('travel_plans.txt') as f:
    for line in f:
        if ':' in line:
            destinations.append(line)

在我看来,您可以通过将国家和城市分成(country, cities)元组来使情况稍微好一些。

with open('travel_plans.txt') as f:
    for line in f:
        if ':' in line:
            country, cities = line.split(':', 1)
            cities = [city.strip() for city in cities.split(',')]
            destinations.append((country, cities))