我有一个变量 num ,列表上有一堆数字
for age in range (0,num)
if num <= age
print ....
else:
print...
如何将它分成两个单独的数字和子列表,如下所示:
num = [1273849173948576379, 7483946582903647829]
答案 0 :(得分:0)
一种解决方案是
[[int(str(j)[i:i+2]) for i in range(0, len(str(j)), 2)] for j in num]
答案 1 :(得分:0)
使用re做同样事情的另一种方法是:
num = [1273849173948576379, 7483946582903647829]
import re
print([list(map(int, re.findall('..?', str(x)))) for x in num])
答案 2 :(得分:0)
列表理解方法会更有效率,但是天真的方法是:
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]]