Check if a digit is present in a list of numbers
Asked Answered
S

4

6

How can I see if a number contains certain digits?

numbers = [2349523234, 12345123, 12346671, 13246457, 134123431]

for number in numbers:
    if (4 in number):
        print(number + "True")
    else:
        print("False")
Sadism answered 24/9, 2015 at 19:46 Comment(0)
J
9

You would have to do string comparisons for this

for number in numbers:
    if '4' in str(number):
        print('{} True'.format(number))
    else:
        print('{} False'.format(number))

It isn't really meaningful to ask if the number 4 is "in" another number (unless you have some particular definition of "in" in mind)

Janejanean answered 24/9, 2015 at 19:47 Comment(0)
C
6

You can convert the number to string and if you want to get the first number that has 4 in it you can use a generator expression within next:

>>> next(i for i in numbers if '4' in str(i))
2349523234

Or you can use a list comprehension if you want to preserve the number that satisfy the condition:

expected_numbers=[i for i in numbers if '4' in str(i)]

But from a mathematical point of view you can generate all the digits using following function:

In [1]: def decomp(num):
   ...:     while num:
   ...:         yield num % 10
   ...:         num = num // 10    

Then you can do the following:

In [3]: numbers = [2349523234, 12345123, 12346671, 13246457, 134123431]

In [4]: [n for n in numbers if any(4==i for i in decomp(n))]
Out[4]: [2349523234, 12345123, 12346671, 13246457, 134123431]
Commotion answered 24/9, 2015 at 19:48 Comment(0)
P
0
number=[number for number in numbers if '4' in str(numbers)]
print(number)
Parabasis answered 26/11, 2023 at 15:48 Comment(0)
P
-1
Klist = []
count = 0
while count < 1000:
    count += 1
    Klist.append(count)
for k in Klist:
    if '6' in str(k):
        print(k)

You create the list and then iterate through the numbers but as a string.

Pointless answered 13/4, 2019 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.