3 回答

TA貢獻1780條經驗 獲得超5個贊
解決方案:
將您的功能更改為:
for item in list:
# Since it's obvious you're checking a string for a number (in string form), you need
# to make sure a space comes after the number (at the beginning of the string) in order
# to avoid incomplete matches.
if item.startswith(num, beg=0, end=len(num)):
...
func_do(item)
結果:
一個)
['2 dogs play', '4 dogs play', '22 dogs play', '24 dogs play', '26 dogs play']
num = '2' # input with no space trailing
使用這種方法的輸出是 func_do('2 dogs play')
乙)
['2 dogs play', '4 dogs play', '22 dogs play', '24 dogs play', '26 dogs play']
num = '2 ' # input with space trailing (user hit spacebar and we didn't `trim()` the input)
使用這種方法的輸出仍然是 func_do('2 dogs play')
謹防:
清理您的輸入,如果您使用到目前為止提供的任何其他方法(或任何檢查輸入后面空格的方法),您將必須警惕用戶輸入一個后面(或前面)有空格的數字。
使用num = input().strip()或:
num = input()
num = num.strip()
另外:這個答案顯然也依賴于您嘗試匹配的用戶輸入字符串,該item字符串位于您的list.

TA貢獻1863條經驗 獲得超2個贊
你需要得到digits來自item然后檢查它是否equal到num:
使用正則表達式:
import re
uList = ['2 dogs play', '4 dogs play', '22 dogs play', '24 dogs play', '26 dogs play']
num = int(input("Enter a num: "))
for item in uList:
if num == int((re.findall(r'\d+', item))[0]):
print(item)
輸出:
Enter a num: 2
2 dogs play
Process finished with exit code 0
編輯:
使用split():
uList = ['2 dogs play', '4 dogs play', '22 dogs play', '24 dogs play', '26 dogs play']
num = input("Enter a num: ") # no conversion to int here
for item in uList:
if num == item.split(' ')[0]: # split and get the digits before space
print(item)
輸出:
Enter a num: 22
22 dogs play
Process finished with exit code 0

TA貢獻1807條經驗 獲得超9個贊
我采用了拆分列表中的每個項目并查詢第一個項目的超級簡單方法。
num = 2
list = ['2 dogs play', '4 dogs play', '22 dogs play', '24 dogs play', '26 dogs play']
for item in list:
number_of_dogs = int(item.split(' ')[0])
if number_of_dogs == num:
print('Doing something!')
代碼非常簡單,僅當列表中的每個項目以數字開頭,后跟一個空格時才有效。
添加回答
舉報