Python v.3将单个元素添加到列表中

时间:2019-02-10 18:55:33

标签: python list

程序获取电话号码,并在列表中添加一位数字

这是我的输入867-5309

这是我的所需输出[8, 6, 7, 5, 3, 0, 9]

这是我得到的,而不是 [[8, 6, 7], [5, 3, 0, 9]]

如何修复?

import re
import num2words

pattern=[r'\d+']
ph=[]

phone = input("Enter phone number ")
print("You entered: ", phone)

for p in pattern:
    match=re.findall(p,phone)
    #print(match)

for i in range(len(match)):
    n=match[i]
    ph.append([int(d) for d in str(n)])
    #print(num2words.num2words(match[i]))

print(ph)

我希望程序最终获取数字并拼出每个数字(但如有必要,这是一个不同的线程),即867-5309,eight six seven five three zero nine

4 个答案:

答案 0 :(得分:2)

为什么不仅是这样:

ph_str = '867-5309'
ph_list = [int(i) for i in ph_str if i.isnumeric()]
print(ph_list)  # [8, 6, 7, 5, 3, 0, 9]

str.isnumeric检查数字(作为字符串)是否可以转换为int。其余的是list comprehension,可直接生成您要查找的列表。

答案 1 :(得分:0)

您将在这里变得很复杂。

首先,您的正则表达式是贪婪的,这意味着其正则表达式匹配所有数字,直到-,然后匹配所有其他数字。

您可以使用不太贪婪的正则表达式来执行此操作,然后匹配项将完全变成所需的输出。

请参见下面的代码。

import re

phone = input("Enter phone number ")
print("You entered: ", phone)


match = re.findall('\d', phone)
print(match)

输出为

['8', '6', '7', '5', '3', '0', '9']

从那里可以执行此操作。

for i in match:
    print(num2words.num2words(i))

输出

eight point zero
six point zero
seven point zero
five point zero
three point zero
zero point zero
nine point zero

剩下的唯一事情就是摆脱“零点”,恐怕我不熟悉num2words。

答案 2 :(得分:0)

这也可能起作用:

number = "867-5309"
lst = []

for i in number:
    if i in "0123456789":
        lst.append(int(i)) 

print(lst) # [8, 6, 7, 5, 3, 0, 9]

答案 3 :(得分:0)

其他一个班轮选项:

[ int(n) for m in s.split('-') for n in m  ]