首页 > 解决方案 > Python v.3 将单个元素添加到列表中

问题描述

程序需要一个电话号码并将单个数字添加到列表中

这是我的输入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

标签: pythonlist

解决方案


为什么不只是这样:

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. 其余的是一个列表推导,它直接生成您正在寻找的列表。


推荐阅读