📜  Python - 改革 K 位元素

📅  最后修改于: 2022-05-13 01:55:40.501000             🧑  作者: Mango

Python - 改革 K 位元素

给定Python列表,将元素改革为在单个元素中包含 K 位数字。

方法 #1:使用切片+ join() + 循环

在这里,我们执行将所有元素连接到单个字符串的任务,然后切片 K 位数字,并重新转换为列表。

Python3
# Python3 code to demonstrate working of
# Reform K digit elements
# Using slicing + join() + loop
  
# initializing list
test_list = [223, 67, 332, 1, 239, 2, 931]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# converting to string
temp = ''.join([str(ele) for ele in test_list])
  
# getting K digit slices
res = []
for idx in range(0, len(temp), K):
    res.append(int(temp[idx: idx + K]))
  
# printing result
print("Reforming K digits : " + str(res))


Python3
# Python3 code to demonstrate working of
# Reform K digit elements
# Using list comprehension + join()
  
# initializing list
test_list = [223, 67, 332, 1, 239, 2, 931]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# converting to string
temp = ''.join([str(ele) for ele in test_list])
  
# getting K digit slices
# using 1 liner list comprehension
res = [int(temp[idx: idx + K]) for idx in range(0, len(temp), K)]
  
# printing result
print("Reforming K digits : " + str(res))


输出
The original list is : [223, 67, 332, 1, 239, 2, 931]
Reforming K digits : [22, 36, 73, 32, 12, 39, 29, 31]

方法 #2:使用列表理解+ join()

在这种情况下,使用列表理解来完成对列表的改造任务。

蟒蛇3

# Python3 code to demonstrate working of
# Reform K digit elements
# Using list comprehension + join()
  
# initializing list
test_list = [223, 67, 332, 1, 239, 2, 931]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# converting to string
temp = ''.join([str(ele) for ele in test_list])
  
# getting K digit slices
# using 1 liner list comprehension
res = [int(temp[idx: idx + K]) for idx in range(0, len(temp), K)]
  
# printing result
print("Reforming K digits : " + str(res))
输出
The original list is : [223, 67, 332, 1, 239, 2, 931]
Reforming K digits : [22, 36, 73, 32, 12, 39, 29, 31]