有沒有辦法縮短這個:
if str(num[p]).find('0') ==
int(-1) and
str(num[p]).find('1') == int(-1)
and str(num[p]).find('2') ==
int(-1) and str(num[p]).find('3')
== int(-1) and
str(num[p]).find('4') == int(-1)
and str(num[p]).find('5') ==
int(-1) and str(num
[p]).find('6') == int(-1) and
str(num[p]).find('7') == int(-1)
and str(num[p]).find('8') ==
int(-1) and str(num[p]).find('9')
== int(-1) and str
(num[p]).find('.') == int(-1):
注意:num[p] 是 for 回圈的一部分,不是錯誤。
uj5u.com熱心網友回復:
import re
if not re.search(r'[\d.]', num[p]):
uj5u.com熱心網友回復:
我會這樣寫:
if not any(c in num[p] for c in "0123456789."):
請注意,如果num[p]已經是字串,str()則不需要(您使用的原始代碼int(-1)也是多余的,因為-1它已經是一個整數)。如果它已經是一個數字,那么整個if陳述句就沒有必要了。
一般來說,in運算子是判斷一個事物是否在另一個事物中的正確方法;只使用像find或者index如果你需要實際索引的方法。該any函式與生成器運算式 ( for ... in ...)相結合,讓您可以將該in檢查多次應用于一系列不同的專案,而無需拼寫出每個專案。
如果這是一個 XY 問題并且您真的想弄清楚是否num[p]可以或不能解釋為 a float,您應該這樣做:
try:
n = float(num[p])
# do whatever
except ValueError:
# do whatever else
uj5u.com熱心網友回復:
你可以把它縮短成類似的東西
if all([
num[p].find(...)
]) == int(-1)
該all函式是一個內置函式,如果傳遞給它的可迭代物件中的所有項都為真,則回傳真
例如,all([1, 2, 3])會回傳True,all([0, 1, 2])不會。
額外注意:
any 如果至少有 1 項為真,則回傳真。
uj5u.com熱心網友回復:
您可以將要檢查的字串添加到陣列中,并對陣列中的所有條目進行 for 回圈檢查:
for char in chars:
if str(num[p]).find(char) == int(-1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400215.html
上一篇:如何在散點圖中顯示相關系數?
下一篇:影像保存到錯誤的檔案路徑
