我想将以下 n 长度列表的字符串元素中的数字提取到原始形式的列表中:
list = ['25 birds, 1 cat, 4 dogs, 101 ants']
output = [25, 1, 4, 101]
我对正则表达式很陌生,所以我一直在尝试以下操作:
[regex.findall("\d", list[i]) for i in range(len(list))]
但是,输出是:
output = [2, 5, 1, 4, 1, 0, 1]
我们实际上并不需要使用正则表达式从字符串中获取数字。
lst = ['25 birds, 1 cat, 4 dogs, 101 ants']
nums = [int(word) for item in lst for word in item.split() if word.isdigit()]
print(nums)
# [25, 1, 4, 101]
不带列表理解的等价:
lst = ['25 birds, 1 cat, 4 dogs, 101 ants']
nums = []
for item in lst:
for word in item.split():
if word.isdigit():
nums.append(int(word))
print(nums)
# [25, 1, 4, 101]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)