Python - 将每个列表元素转换为键值对
给定元素列表,将每个元素转换为键值对字典,平均划分数字。
Input : test_list = [2323, 82, 129388, 234, 95]
Output : {23: 23, 8: 2, 129: 388, 2: 34, 9: 5}
Explanation : Digits distributed equally to keys and values.
Input : test_list = [2323, 82, 129388]
Output : {23: 23, 8: 2, 129: 388}
Explanation : Digits distributed equally to keys and values.
方法:使用列表切片+循环
在这种情况下,我们通过将每个元素的切片值除以键和值的数字的一半来形成键值对。
Python3
# Python3 code to demonstrate working of
# Convert each list element to key-value pair
# Using loop + list slicing
# initializing list
test_list = [2323, 82, 129388, 234, 95]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
for ele in test_list:
# constructing key and values
mid_idx = len(str(ele)) // 2
key = int(str(ele)[:mid_idx])
val = int(str(ele)[mid_idx:])
# item assignment
res[key] = val
# printing result
print("Constructed Dictionary : " + str(res))
输出
The original list is : [2323, 82, 129388, 234, 95]
Constructed Dictionary : {23: 23, 8: 2, 129: 388, 2: 34, 9: 5}