python - 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
解决方案
为什么不只是这样:
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
. 其余的是一个列表推导,它直接生成您正在寻找的列表。
推荐阅读
- javascript - 无法在 svg 中获得鼠标指针的精确 xy 坐标(在路径标签上)
- javascript - 使用 Karma 时如何访问我的规范文件中的 Puppeteer 对象?
- android - 我想在布局中添加带有建议的 SearchView,而不是在 android 的操作栏中
- angular5 - Angular 5:我们如何使用相同的指令来限制输入字段并在 html 的标签中显示文本
- java - Liquibase maven:spring-boot启动时找不到更改日志位置
- python-3.x - 使用我在类的构造函数中创建的列表?
- python - 从 crontab 运行程序时无法加载本机 TensorFlow 运行时
- pdf - nutch solrindex 添加 1 个文档
- angularjs - Stateprovider 在 Cordova angularJS 应用程序中不起作用
- api - 如何计算每个频道的 youtube 喜欢、不喜欢和评论数