我有一个整体列表:
l1 = [8, 2, 2, 6, 10, 14, 18, 2]
如何测试单个数字?如果不是单个数字,则拆分为单个数字
for i in l1:
if len(i) > 1:
something
所以新名单将是:
l1 = [8, 2, 2, 6, 1, 0, 1, 4, 1, 8, 2]
答案 0 :(得分:2)
您可以使用字符串:
list(''.join(map(str, l1)))
它将数字转换为字符串,将它们连接起来,然后获取字符列表。
>>> l1 = [8, 2, 2, 6, 10, 14, 18, 2]
>>> list(''.join(map(str, l1)))
['8', '2', '2', '6', '1', '0', '1', '4', '1', '8', '2']
答案 1 :(得分:1)
也许是一个发电机:
def split_digits(numbers):
for number in numbers:
for digit in str(number):
yield int(digit)
print list(split_digits([8, 2, 2, 6, 10, 14, 18, 2]))
答案 2 :(得分:1)
您可以将每个元素转换为字符串,然后添加每个字符
l1 = [8, 2, 2, 6, 10, 14, 18, 2]
l2 = []
for i in l1:
s = str(i)
for digit in s:
l2.append(int(digit))
答案 3 :(得分:1)
这样的事情怎么样,不使用字符串:
def convert(my_list):
new_list = []
for ele in my_list:
new_list.extend(split(ele))
return new_list
def split(x):
if x == 0:
return [0]
result = []
while x:
result.append(x % 10)
x /= 10
return result[::-1]
结果:
>>> convert(l1)
[8, 2, 2, 6, 1, 0, 1, 4, 1, 8, 2]
>>> convert([133, 34, 0, 44])
[1, 3, 3, 3, 4, 0, 4, 4]
答案 4 :(得分:1)
for i, num in enumerate(nums):
nums[i:i+1] = [int(d) for d in str(num)]