2017-09-24 95 views
-2

我试图返回包含5的所有数字,包括起始值和结束值。我创建了一个包含所有数字的字符串列表。然而,我很困惑我如何获得值并将它们添加到新列表中。 例如,giveMeFive(42,75)将返回列表[45,50,51,52,53,54,55,56, 57,58,59,65,75]返回所有包含5的数字

def giveMeFive(): 
    num1 = int(input("Whats the first number?")) 
    num2 = int(input("Whats the second number?")) 
    lst = str(list(range(num1, num2 + 1))) 
    print(lst.find("5")) 
    newLst = [] 
    for x in lst: 
     if(lst(x) == "5"): 
      #stuck 
+0

请分享投入和预期回报值的例子。 – bfontaine

+0

这是许多不同问题的重复。搜索“python in”和“python append list”。 –

+1

可能重复[检查字符串中的特殊字符?](https://stackoverflow.com/questions/9884958/check-special-character-in-string) –

回答

3

在你的代码,你正在做:

lst = str(list(range(num1, num2 + 1))) 

这是将您的列表转换为字符串,然后你迭代字符串。相反,你的代码应该是这样的:实现这一目标是通过列表理解表达

lst = list(range(num1, num2 + 1)) # No need to type-cast it to string. 
            # Infact you don't even need `list` here. 
newLst = [] 
for x in lst: 
    #   v type-cast your number to string 
    if "5" in str(x): # check "5" is present in your number string 
     newLst.append(x) # append your number to the list 

更好的办法。例如:

>>> number1 = 5 
>>> number2 = 31 

>>> [i for i in range(number1, number2+1) if "5" in str(i)] 
[5, 15, 25] 
1

这也适用

num1 = int(input("Input no 1")) 
num2 = int(input("Input no 2")) 

lst = map(str, range(num1, num2+1)) 
#  ^convert list of numbers to list of "number strings" 

List5 = [] 
for i in lst: 
    if "5" in i: 
     List5.append(i) 
+0

我添加了可用于OP的替代版本的代码。 @Kieron请看看它。并且,欢迎来到SO :) –

+0

感谢@MoinuddinQuadri,这就是为什么你有20k代表,而我只有31 :) 可能必须添加一个else:语句来惹恼你/满足我的坏习惯:P – Kieron

相关问题