构造等位数元组的Python程序
给定元素列表,将元组列表划分为相似的数字元组对。
Input : test_list = [5654, 223, 982143, 34, 1021]
Output : [(56, 54), (2, 23), (982, 143), (3, 4), (10, 21)]
Explanation : Element in tuples equidistributed.
Input : test_list = [5654, 223, 1021]
Output : [(56, 54), (2, 23), (10, 21)]
Explanation : Element in tuples equidistributed.
方法 #1:使用循环 + 切片 + str()
在这里,我们通过获取mid-idx然后从mid切片来执行除法任务,使用str()将最初的整数拆分为一个字符串。
Python3
# Python3 code to demonstrate working of
# Construct Equidigit tuples
# Using loop + slicing str()
# initializing list
test_list = [5654, 223, 982143, 34, 1021]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# getting mid element
mid_idx = len(str(sub)) // 2
# slicing Equidigits
el1 = str(sub)[:mid_idx]
el2 = str(sub)[mid_idx:]
res.append((int(el1), int(el2)))
# printing result
print("Equidigit tuples List : " + str(res))
输出:
The original list is : [5654, 223, 982143, 34, 1021]
Equidigit tuples List : [(56, 54), (2, 23), (982, 143), (3, 4), (10, 21)]