返回包含5的所有数字

时间:2017-09-24 20:27:20

标签: python

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

node.addEventListener("mouseover", function() {
    // Load data here
}, {once : true});

2 个答案:

答案 0 :(得分: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

实现这一目标的更好方法是通过 list comprehension 表达式。例如:

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

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

答案 1 :(得分: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)