如何在python列表中拆分名称和电话号码?

时间:2017-08-01 15:36:23

标签: python python-3.x

我正在尝试获取此格式的列表列表,并将名称和电话号码分开

[['Jackson, Janet', '313-1352'], ['James, Lebron', '457-6221'], ['Manfredi, Ralph', '872-2221'], ['Prakash, Varun', '312-5398']]

我目前正在使用这种格式

['Jackson, Janet 313-1352', 'James, Lebron 457-6221', 'Manfredi, Ralph 872-2221', 'Prakash, Varun 312-5398']

我一直在尝试这些逻辑

from myDatabasefile import *

b = []
contactlist = select()

print (contactlist)


for row in contactlist:
    b.append(row)
    print (row)
print(b)

5 个答案:

答案 0 :(得分:3)

如果所有电话号码仅包含数字和短划线,您可以使用:

import re

rgx = re.compile(r'\s+(?=[\d-]+$)')

result = [rgx.split(x,1) for x in input]

其中input因此是您的输入字符串列表。它生成以下列表:

>>> [rgx.split(x,1) for x in input]
[['Jackson, Janet', '313-1352'], ['James, Lebron', '457-6221'], ['Manfredi, Ralph', '872-2221'], ['Prakash, Varun', '312-5398']]

但如前所述,只有在上述假设下才能正常运作。最好的是,如果电话号码包含空格,那么它仍然可以工作:

import re

rgx = re.compile(r'\s+(?=[\d\s-]+$)')

result = [rgx.split(x,1) for x in input]

对于电话号码中带有空格的输入,它会显示:

>>> input = ['Jackson, Janet 313-13 52', 'James, Lebron 457-6 22 1', 'Manfredi, Ralph 872-222 1', 'Prakash, Varun 312-5 3 9 8']
>>> [rgx.split(x,1) for x in input]
[['Jackson, Janet', '313-13 52'], ['James, Lebron', '457-6 22 1'], ['Manfredi, Ralph', '872-222 1'], ['Prakash, Varun', '312-5 3 9 8']]

答案 1 :(得分:1)

您能保证电话号码始终为7位吗?如果是的话,

contactList = []
for item in listOfContacts:
     contact = []
     phoneNumber = item[-8:] #get the phone number
     contactInfo = item.split() #split on the space
     contactInfo.pop() #pop the phone number
     contactName = " ".join(contactInfo)
     contact.append(contactName)
     contact.append(phoneNumber)
     contactList.append(contact)

这可能是更有效的方法,但在我的头脑中,这是非常简洁的。

答案 2 :(得分:1)

如果电话号码始终为8位数,您可以尝试:

contact_list = [[x[:-9], x[-8:]] for x in initial_list]

答案 3 :(得分:0)

没有正则表达式的单行解决方案:

s = ['Jackson, Janet 313-1352', 'James, Lebron 457-6221', 'Manfredi, Ralph 872-2221', 'Prakash, Varun 312-5398']

new_s = [[' '.join(i.split()[:2])]+[i.split()[-1]] for i in s]

输出:

[['Jackson, Janet', '313-1352'], ['James, Lebron', '457-6221'], ['Manfredi, Ralph', '872-2221'], ['Prakash, Varun', '312-5398']]

答案 4 :(得分:0)

import re
l = ['Jackson, Janet 313-1352', 'James, Lebron 457-6221', 'Manfredi, Ralph 872-2221', 'Prakash, Varun 312-5398']
[ re.search(r'(.*) (\d+\-\d+)', s).groups() for s in l ]

输出:

[('Jackson, Janet', '313-1352'),
 ('James, Lebron', '457-6221'),
 ('Manfredi, Ralph', '872-2221'),
 ('Prakash, Varun', '312-5398')]