如何将整数列表拆分为数字整数列表?
How do I split a list of integers into a list of digit integers?
考虑列表
test_list = [14, 12, 10, 8]
我想remake/split这个变成
test_list = [1, 4, 1, 2, 1, 0, 8]
我想将列表拆分成单个数字。
这应该可行 - 遍历列表中的数字,并将每个数字分成一个数字列表,其中的每个元素都附加到一个数字数组。
digits = []
for num in test_list:
digits.extend([int(i) for i in str(num)])
像这样? (你想拆分整数)
newList = [int(y) for x in test_list for y in list(str(x))]
有点棘手:
b = [int(digit) for digit in ''.join((str(item) for item in a))]
print(b)
输出:
[1, 4, 1, 2, 1, 0, 8]
这是一种不使用字符串作为中介的替代方法:
test_list = [14, 12, 10, 8]
output_list = []
for number in test_list:
if number < 10:
output_list.append(number)
else:
output_list.extend([number // 10, number % 10])
print(output_list)
考虑列表
test_list = [14, 12, 10, 8]
我想remake/split这个变成
test_list = [1, 4, 1, 2, 1, 0, 8]
我想将列表拆分成单个数字。
这应该可行 - 遍历列表中的数字,并将每个数字分成一个数字列表,其中的每个元素都附加到一个数字数组。
digits = []
for num in test_list:
digits.extend([int(i) for i in str(num)])
像这样? (你想拆分整数)
newList = [int(y) for x in test_list for y in list(str(x))]
有点棘手:
b = [int(digit) for digit in ''.join((str(item) for item in a))]
print(b)
输出:
[1, 4, 1, 2, 1, 0, 8]
这是一种不使用字符串作为中介的替代方法:
test_list = [14, 12, 10, 8]
output_list = []
for number in test_list:
if number < 10:
output_list.append(number)
else:
output_list.extend([number // 10, number % 10])
print(output_list)