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!')
代码非常简单,仅当列表中的每个项目以数字开头,后跟一个空格时才有效。
添加回答
举报