Python - 从数字中提取后 K 位数字
给定一个整数列表,从中提取后 K 位数字。
Input : test_list = [5645, 23567, 34543, 87652, 2342], K = 2
Output : [45, 67, 43, 52, 42]
Explanation : Last 2 digits extracted.
Input : test_list = [5645, 23567, 34543, 87652, 2342], K = 4
Output : [5645, 3567, 4543, 7652, 2342]
Explanation : Last 4 digits extracted.
方法 #1:使用列表理解+ %运算符
在这种技术中,我们用 10^K 对每个数字求模以获得每个数字所需的最后 K 位数字。
Python3
# Python3 code to demonstrate working of
# Extract Rear K digits from Numbers
# Using list comprehension + % operator
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# Getting remainder for each element
res = [ele % (10 ** K) for ele in test_list]
# printing result
print("Rear K digits of elements ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Rear K digits from Numbers
# Using str() + slicing
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# getting integer using int() after slicing string
res = [int(str(idx)[-K:]) for idx in test_list]
# printing result
print("Rear K digits of elements ? : " + str(res))
输出
The original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]
方法 #2:使用str() + 切片
在这里,我们使用列表切片执行获取后部元素的任务,并且 str() 用于将每个元素转换为字符串。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Rear K digits from Numbers
# Using str() + slicing
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# getting integer using int() after slicing string
res = [int(str(idx)[-K:]) for idx in test_list]
# printing result
print("Rear K digits of elements ? : " + str(res))
输出
The original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]