如何查找从1到100范围内的所有包含特定数字的数字?

时间:2019-04-26 18:17:36

标签: python python-3.x python-2.7

我在1个列表中有1到100个项目的列表。

查询1:

假设我要查找1到100之间的6个新列表 应该有-6,16,26,36,46,56,60,61,62,63,64,65,66,67,68,69,76,86,96
我们如何实现这一目标?

查询2:

具体数字可以是我们选择的任何数字,例如我有4个 那么新列表应为-4,14,24,34,40,41,42,43,44,45,46,47,48,49,54,64,74,84,94

那么我们可以为两者都使用通用逻辑,还是需要对任何特定数字使用不同的逻辑?

编辑

这是我到目前为止尝试过的,

z = [1,2,3,4,5,6,7,8,9,10] 
for i in z: 
    if i == 6: 
        print(i)

我只能从1到10拿到它,但不能从1到100拿到它。

4 个答案:

答案 0 :(得分:4)

这是程序,

x = list(range(1, 101)) 
n = str(input("Enter a number: "))
output = [i for i in x if n in str(i)]
print (output)

输出:

  

输入数字:4

     

输出:[4, 14, 24, 34, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 54, 64, 74, 84, 94]

您选择的数字n4

  

输入数字:6

     

输出:[6, 16, 26, 36, 46, 56, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 76, 86, 96]

您选择的数字n6

  

x = list(range(1, 101))

  • range()函数可用于创建长列表。然后list()函数使用此序列中的数字来创建列表。

希望这会有所帮助!

答案 1 :(得分:1)

您可以使用模(%)和整数除法(//)获得范围内的所有数字:

x = range(1,101)
b = [i for i in x if i % 10 == 6 or i // 10 == 6]
print(b)

模数部分将为您提供在“ 1”中具有6的任何值-整数除法将获得在“十”位具有6的所有值:

[6, 16, 26, 36, 46, 56, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 76, 86, 96]

答案 2 :(得分:0)

我现在知道了:

[i for i in x if i % 10 == 6]          
# [6, 16]


[i for i in x if i % 10 == 4]
# [4, 14]

答案 3 :(得分:0)

# For k = 0
k = 0
print([i for i in range(k,101,10)])   #Only for zero

# For k > 0  and GENERIC
k = 6
print([i for i in range(k,101,10)])
# doesn't include 60-69
#### Output  ####
#[6, 16, 26, 36, 46, 56, 66, 76, 86, 96]


print([i for i in range(k,101,10)] + [i for i in range(k*10,(k+1)*10)])
# this includes all 6 poosible in the range 1-100
#### Output  ####
#[6, 16, 26, 36, 46, 56, 66, 76, 86, 96,60, 61, 62, 63, 64, 65, 66, 67, 68, 69]


list_of_fours = [i for i in range(4,101,10)] + [i for i in range(4*10,(4+1)*10)]
list_of_six = [i for i in range(6,101,10)] + [i for i in range(6*10,(6+1)*10)]
print(list_of_fours+list_of_six)
#if only concern is 4 and 6
#### Output  ####
# list_of_fours = [4, 14, 24, 34, 44, 54, 64, 74, 84, 94, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
# list_of_fours = [6, 16, 26, 36, 46, 56, 66, 76, 86, 96, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
#[4, 14, 24, 34, 44, 54, 64, 74, 84, 94, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 6, 16, 26, 36, 46, 56, 66, 76, 86, 96]