亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不檢測具有相同數字的數字的情況下檢查列表中的數字?

如何在不檢測具有相同數字的數字的情況下檢查列表中的數字?

繁花不似錦 2021-12-21 16:15:53
假設我有一個列表:[2 dogs play, 4 dogs play, 22 dogs play, 24 dogs play, 26 dogs play] 我有一個表達式要求用戶輸入一個數字,它存儲在變量中,num我的代碼中有一個條件,for item in list:     if num in item:        ....        do something to item我的問題是,如果用戶輸入 2,代碼也會對有 22、24 和 26 的項目做一些事情,因為它有 2,當我只希望它對只有 2 的項目做一些事情時。我該如何實現?
查看完整描述

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.


查看完整回答
反對 回復 2021-12-21
?
小唯快跑啊

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


查看完整回答
反對 回復 2021-12-21
?
函數式編程

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!')

代碼非常簡單,僅當列表中的每個項目以數字開頭,后跟一個空格時才有效。


查看完整回答
反對 回復 2021-12-21
  • 3 回答
  • 0 關注
  • 209 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號