返回由.split()元素组成的python中的列表

时间:2013-09-20 04:53:31

标签: python list

在下面的代码中,getreport是由/t/n格式化的文本项。 我正在尝试输出电话号码列表,但返回的列表会像这样返回:['5','5','5','7','8','7', ...]等,而不是类似['5557877777']。这有什么不对?

def parsereport(getreport):
listoutput = []
lines = re.findall(r'.+?\n' , getreport) #everything is in perfect lines
for m in lines:
    line = m
    linesplit = line.split('\t')  # Now I have a list of elements for each line
    phone = linesplit[0]  # first element is always the phone number ex '5557777878'
    if is_number(linesplit[10]) == True:
            num = int(linesplit[10])
            if num > 0:
                listoutput.extend(phone) 

我尝试将print(手机)用于测试,它看起来很棒,并返回'5557877777'等行,但返回列表= ['5','5'等]并且数字被分开。

return listoutput

2 个答案:

答案 0 :(得分:6)

您将使用listoutput.append()功能代替listoutput.extend()

>>> p='12345'
>>> l=[]
>>> l.extend(p)
>>> l
['1', '2', '3', '4', '5']
>>> ll = []
>>> ll.append(p)
>>> ll
['12345']

extend function: 通过附加给定列表中的所有项目来扩展列表

答案 1 :(得分:0)

>>> Numbers = ['1', '2', '3', '4', '5']
>>> NumbersJoined = []
>>> NumbersJoined.append(''.join(Numbers))
>>> print NumbersJoined
['12345']