Check if a digit is present in a list of numbers

拥有回忆 提交于 2019-12-18 08:47:27

问题


How can I see if an index contains certain numbers?

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

for number in numbers:
    if (4 in number):
        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]



回答3:


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.



来源:https://stackoverflow.com/questions/32769699/check-if-a-digit-is-present-in-a-list-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!