[英]How to split number and list into sublist in python
我有一个变量num ,列表上有一堆数字
num = [1273849173948576379, 7483946582903647829]
如何将其拆分为两个单独的数字和子列表,如下所示:
[[12,73,84..],[74,83,94..]]
一种解决方案是
[[int(str(j)[i:i+2]) for i in range(0, len(str(j)), 2)] for j in num]
使用re做相同事情的另一种方法是:
num = [1273849173948576379, 7483946582903647829]
import re
print([list(map(int, re.findall('..?', str(x)))) for x in num])
列表理解方法会更有效,但是简单的方法是:
num = [1273849173948576379, 7483946582903647829]
new_list = []
for number in num:
# Converting each number into string so that we can slice using index
str_number = str(number)
# Empty list for storing pieces of each number in num
tmp = []
# Using for loop to increment from start i.e. 0 till < length of string
# and each time increment is by 2
for i in range(0, len(str_number), 2):
# Slicing the index to get two digit number and appending to tmp
int_number = str_number[i:i+2]
tmp.append(int(int_number))
# Finally done with one of the number in num so, appending to new_list
new_list.append(tmp)
new_list
输出:
[[12, 73, 84, 91, 73, 94, 85, 76, 37, 9],
[74, 83, 94, 65, 82, 90, 36, 47, 82, 9]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.