[英]Extract number from a list with less than 4 digits, and to each number append a string to the beginning and to the end
[英]Extract only digits for each string from list of strings?
目前,我正在做一些網絡抓取。 我的一個提取會返回網站上每個項目的完整ID。
看起來像:
['ID: 1234', 'ID: 456', 'ID: 8899']
我想運行一個迭代器,它只返回列表中每個項的整數值。
喜歡(首選) :
[1234, 456, 8899]
我已經看到許多與提取整數有關的問題,但他們都建議解決方案將每個數字作為新列表中的索引返回,因此(當前) :
[1,2,3,4,4,5,6,8,8,9,9]
我可以用:
testList = []
for i in list:
id = re.findall('\d+', i)
testList.append(id)
但我正在尋找額外的步驟,以便在首選輸出中獲得它。 任何列表理解與正則表達式組合建議?
此外,如果這是重復,將非常感謝鏈接。
先感謝您。
l=['ID: 1234', 'ID: 456', 'ID: 8899']
print([int(x.split(':')[1]) for x in l])
輸出繼電器
[1234, 456, 8899]
最簡單的方法是拆分列表中的每個元素,因為它分隔'ID:'和帶有空格''的數字:
lst = ['ID: 1234', 'ID: 456', 'ID: 8899']
testList = []
for ele in lst:
id_num = ele.split()[1]
testList.append(id_num)
str.isnumeric
檢查字符串是否可以解釋為數字。 如果你試圖得到數字,無論你應該使用這個位置。
lst = ['ID: 1234', 'ID: 456', 'ID: 8899']
nums = list(map(lambda s:int(''.join([c for c in s if c.isnumeric()])), lst))
print(nums) # [1234, 456, 8899]
但是如果你知道格式總是有ID:
那么bitto的答案是最好的。
test = []
id = ['ID: 1234', 'ID: 456', 'ID: 8899']
test.append([int(x.split(':')[1]) for x in id])
print(test)
您還可以使用列表解析和元組解包:
>>> l = ['ID: 1234', 'ID: 456', 'ID: 8899']
>>> [int(y.lstrip()) for _, y in (z.split(':') for z in l)]
[1234, 456, 8899]
在轉換為整數之前,還使用str.lstrip()
從字符串左側剝離空格。
使用正則表達式查找所有匹配的條目。 下面的模式捕獲列表中的所有匹配數字。 然后,map將捕獲列表中的每個輸入字符串轉換為整數。
>>> import re
>>> data = "['ID: 1234', 'ID: 456', 'ID: 8899']"
>>> map(lambda x: int(x), re.findall("'ID: (\d+)'", data))
[1234, 456, 8899]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.