简体   繁体   English

检查数字列表中是否存在数字

[英]Check if a digit is present in a list of numbers

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

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) 询问数字4是否在“另一个数字”中是没有意义的(除非你对“in”有一些特定的定义)

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 : 您可以将数字转换为字符串,如果您想获得其中包含4的第一个数字,您可以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]
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. 您创建列表然后迭代数字,但作为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM