簡體   English   中英

清理列表以僅保留整數

[英]cleaning a list to only keep integers

請耐心等待,我正處於學習編碼的早期階段。 我的上一條指南有問題。

function clean 應該執行以下操作:

- 刪除丟失的項目(例如 1,2,,3)

- 刪除標記為 None 或為空字符串的項目 - 刪除不是數字的項目

- 但是,如果該項目是一個字符串,但一個有效的數字,保留它(例如'1.1','3')

- 將每個有效數字轉換為浮點數

到目前為止我有

def clean(csv_list):
  no_none = list(filter(None, csv_list))
  only_numbs = list(filter(str.isdigit, no_none))
return only_numbs

我一直在弄清楚如何在列表中保留表示整數的字符串。

csv = "a, 1, '-2', 2.35, None,, 4, True"
print(clean(csv))
# output is [1.0, -2.0, 2.35, 4.0]

不久與re.findall function:

import re

s = "a, 1, '-2', 2.35, None,, 4, True"
numbers = [float(n) for n in re.findall(r'-?\d+(?:\.\d+)?', s)]
print(numbers)    # [1.0, -2.0, 2.35, 4.0]
import re
import numpy as np
string = "a,'4', as, 5.0, -12, '42', ,, g"
results = np.array(re.findall(r'-?\d+(?:\.\d+)?', string))

print(results.astype(float))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM