Check if a digit is present in a list of numbers

2019-01-28 11:23发布

问题:

How can I see if an index contains certain numbers?

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

for number in nummers:
    if (4 in nummer):
        print(number + "True")
    else:
        print("False")

回答1:

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")

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)



回答2:

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]