数据结构组织数字和单词python

时间:2014-03-21 21:17:02

标签: python

Winnipeg,MB [4988,9715] 564473
1611 686 1833 1446 550 1279

我试图将我的代码组织成4种不同的数据结构。一个是名称和州(Winnipeg,MB),第二个是位置([4988,9715]),第三个是人口(564473),第四个是里程(1611 686 1833 1446 550 1279)。文件中的行显示在上面。

这是我每行的代码(我也有一些打印语句来检查我的代码):

import re
#writing a program that stores data into its appropriate data structure

#this function parses through each line to find the name

def parseName(s):
    #setting up variables as lists, strings, and index
    city = []
    index = 0
    cityList = []
    cityCordinate= []
    population = []
    milage = []
    #spliting characters
    listSplit = re.split('\W+', s)
    print listSplit
    #checking to see if first element in list is a letter
    if listSplit[0].isalpha:
        print "alpha"
        cityCordinate = listSplit[2:4]
        cityCordinateFinal =  map(int, cityCordinate)
        population.append(listSplit[4])
        print cityCordinateFinal
        print populationFinal
        #running through line to see if it is a word
        for i in listSplit:
            print i 
            if i.isalpha():
                city.append(i)

        #joining city name and state together and appending to new list        
        cityList.append(", ".join(city))
        print cityList
    #checks milage
    elif listSplit[0].isdigit():
        for i in listSplit:
            milage.append(i)
        print milage

出于某种原因,如果我插入parseName(" 1611 686 1833 1446 550 1279")它会打印

['1611', '686', '1833', '1446', '550', '1279']
alpha
[1833, 1446]
['550']
1611
686
1833
1446
550
1279
['']

它正在进入第一个if语句,某种方式是真的吗?当分组列表的第一个元素是数字而不是字母(is.alpha)时,有人可以向我解释这是如何可行的。如果我输入parseName(" Winnipeg,MB [4988,9715] 564473"),它适用于我的第一行。它会回来:

alpha
[4988, 9715]
['564473']
Winnipeg
MB
4988
9715
564473
['Winnipeg, MB']

它正确地做了。有人可以指出错误吗? 而且我还有另一个问题,当我开始有多行这样的milage:

1958 1452 1484 1799 921 1703 1043 1096 1226 1005 2026 2152 1330 1287 471 204 1174 1540 1507 1593 1308 1427 1415 1227 1132 1892 2082 887 1338

将每个milage存储到每个城市/坐标/群体是否有问题? 我的代码中也有拼写错误,请原谅我:)

1 个答案:

答案 0 :(得分:1)

你不是在调用isalpha,你只是引用该方法(因为它存在,返回为True)。

您需要使用parantheses来调用该方法,例如:

if listSplit[0].isalpha():

有关更多详细信息,请参阅命令行解释器的输出:

>>> ''.isalpha
<built-in method isalpha of str object at 0x7f6448b02508>
>>> ''.isalpha()
False