How would I check if the first digits in each element in a list are the same?
for i in range(0,len(lst)-1):
if lst[i] == lst[i+1]:
return True
I know that this checks for if the number before is equal to the next number in the list, but I just want to focus on the first digit.
You can use math.log10
and floor division to calculate the first digit. Then use all
with a generator expression and zip
to test adjacent elements sequentially:
from math import log10
def get_first(x):
return x // 10**int(log10(x))
L = [12341, 1765, 1342534, 176845, 1]
res = all(get_first(i) == get_first(j) for i, j in zip(L, L[1:])) # True
For an explanation of how this construct works, see this related answer. You can apply the same logic via a regular for
loop:
def check_first(L):
for i, j in zip(L, L[1:]):
if get_first(i) != get_first(j):
return False
return True
res = check_first(L) # True
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加